Vanilla JavaScript string endsWith

β€” 3 minute read

permalink

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 permalink

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 permalink

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 permalink

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! permalink

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