DEV Community

Cover image for Vanilla JavaScript string endsWith
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript string endsWith

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)

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

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

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

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

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

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.

var 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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)