This post will discuss how to check whether a string ends with another string in JavaScript.

1. Using endsWith() method

The recommended solution is to use the JavaScript native method endsWith() to determine whether the string begins with a specified string. This is demonstrated below:

 
This method was added to the ES6 specification and may not be available in all JavaScript implementations yet. However, you can use the following polyfill from MDN:

 
Alternatively, you can use the Lodash or Underscore.string library, that also offers the _.endsWith method. It checks whether the string ends with a given target string.

Download Code

2. Using lastIndexOf() method

Here, the idea is to find the index of the last occurrence of the given string. The following code example shows how to implement this using the lastIndexOf() method.

Download  Run Code

 
Since the lastIndexOf() method returns -1, the code will fail when the string’s length is one less than the length of the target substring. Here’s how to handle this:

Download  Run Code

 
Alternatively, with the indexOf() method, you can do like:

Download  Run Code

3. Using substring() or slice() method

The substring() method is used to get the string between the specified indexes. This can be used as follows:

Download  Run Code

 
Alternatively, the slice() method can be called in place of the substring() method. The advantage of using the slice() method over the substring() method is that you can also use the negative indexes with it, as demonstrated below:

Download  Run Code

4. Using Regex

Another plausible way to check whether a string ends with another substring is by using regular expressions. Be careful with this approach as Regexes are costly, and you might run into performance problems.

Download  Run Code

 
Or use match() method, which match a string against a regular expression:

Download  Run Code

That’s all about determining whether a string ends with another string in JavaScript.