Vanilla JavaScript string endsWith

โœ๏ธ

How to use Vanilla JavaScript string.endsWith() function

6 May, 2020 ยท 2 min read

Yesterday we had a look at the startsWith() function, and today we are looking at its brother the endsWith() function! As the name suggests, this one looks if a string ends with a specific substring.

Using endsWith function in JavaScript

To use the function, we need to have a string then we can call the string.endsWith('substring') function and we will get a boolean value in return (true/false)

const string = "Life is what happens when you're busy making other plans.";

// Check if it ends with `plans.`
console.log(string.endsWith('plans.'));
// true

As we saw in the startsWith() function this one is also case sensitive.

const string = "Life is what happens when you're busy making other plans.";

// Check if it ends with `Plans.`
console.log(string.endsWith('Plans.'));
// false

Using an offset search position on endsWith

The endsWith() also has the option to offset, but from the end, so let's say we know the string always ends with "plans". We can then offset by six characters using the position attribute.

const string = "Life is what happens when you're busy making other plans.";

// Check if it ends with `other`
console.log(string.endsWith('Life', 4));
// true

With this position, keep in mind it will cap the string after four characters from the starting point!

Feel free to play with this Codepen:

See the Pen Vanilla JavaScript string endsWith by Chris Bongers (@rebelchris) on CodePen.

Browser Support

This function works in all browsers but not in IE ๐Ÿ˜ข. We can use this polyfill to help IE.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API