How do I check if a string ends with a specific substring in JavaScript?
Rashid D
rashid d profile pic

In JavaScript, there are multiple ways to check if a string ends with a specific substring. Here are a few common approaches: 1. Using theendsWith() method:

1
2
3
4
5

   const str = "Hello, World!";
   const substring = "World!";
   const endsWith = str.endsWith(substring);
   

TheendsWith() method returnstrue if the string ends with the specified substring; otherwise, it returnsfalse. This method is case-sensitive, so ensure that the case matches. 2. Using theslice() method:

1
2
3
4
5

   const str = "Hello, World!";
   const substring = "World!";
   const endsWith = str.slice(-substring.length) === substring;
   

Theslice() method extracts a portion of the string. By using a negative index with theslice() method, you can extract a substring from the end of the string. This approach compares the extracted substring with the desired substring using strict equality (===) to determine if the string ends with the specified substring. 3. Using a regular expression (regex):

1
2
3
4
5
6

   const str = "Hello, World!";
   const substring = "World!";
   const regex = new RegExp(substring + "$");
   const endsWith = regex.test(str);
   

This approach uses a regular expression with the$ anchor, which matches the end of the string. The regular expression is created with theRegExp constructor, and thetest() method is called on the regex to check if the string matches the pattern. Choose the method that suits your needs and adjust the code as necessary to fit your specific use case. Remember to account for case sensitivity and consider any performance implications when working with large strings.