Categories
JavaScript Answers

How to Check if a JavaScript String Ends with a Given String?

Spread the love

Checking if a JavaScript string ends with a given string is something that we may have to do sometimes.

In this article, we’ll look at how to check if a JavaScript string ends with a given string.

String.prototype.indexOf

We can use the string’s indexOf method to check the index of the string.

For instance, we can write:

const endsWith = (str, suffix) => {  
  return str.indexOf(suffix, str.length - suffix.length) !== -1;  
}  
console.log(endsWith('hello world', 'world'))

We call indexOf with the suffix , which is the string we’re searching for.

And we start searching from the index str.length — suffix.length .

This will make sure the suffix is at the end if it exists.

If indexOf returns anything other than -1, then suffix is at the end of the string.

Otherwise, it’s not at the end of the string.

Using the substr Method

We can use the substr method to check whether a substring is at the location we want.

To do this, we write:

const endsWith = (str, suffix) => {  
  return str.length >= suffix.length && str.substr(str.length - suffix.length) === suffix;  
}  
console.log(endsWith('hello world', 'world'))

In the endsWith function, we check if str.length >= suffix.length so that we know str is longer than suffix .

If that’s true , then we call substr with str.length — suffix.length to get the substring starting with index str.length — suffix.length which is where the suffix would start if it’s at the end.

If the returned value is equal to suffix , then we know suffix is at the end of str .

Using the lastIndexOf Method

Also, we can use the lastIndexOf method to get the index of the last instance of a given substring.

For instance, we can write:

const endsWith = (str, suffix) => {  
  const lastIndex = str.lastIndexOf(suffix);  
  return (lastIndex !== -1) && (lastIndex + suffix.length === str.length);  
}  
console.log(endsWith('hello world', 'world'))

We call lastIndexOf with suffix to get the index of the start of the last instance of suffix .

Then if lastIndex isn’t -1 and that lastIndex + suffix.length is the same as str.length , we know suffix is located at the end of str .

String.prototype.endsWith

Strings come with the endsWith method that lets us check whether the string we called the method on ends with a given substring.

For instance, we can write:

console.log('hello world'.endsWith('world'))

We just call endsWith with the substring we’re checking for.

Conclusion

We can check if a string ends with a given substring with various string methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *