Subscribe

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 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter