1. Using the
1 2 3 4 5
const str = "Hello, World!"; const substring = "World!"; const endsWith = str.endsWith(substring);
endsWith() method returns
true if the string ends with the specified substring; otherwise, it returns
false. This method is case-sensitive, so ensure that the case matches.
2. Using the
1 2 3 4 5
const str = "Hello, World!"; const substring = "World!"; const endsWith = str.slice(-substring.length) === substring;
slice() method extracts a portion of the string. By using a negative index with the
slice() 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 the
RegExp constructor, and the
test() 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.