How do I check if a string ends with a specific substring in JavaScript?Rashid D
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.
Similar Questions
How do I check if a string ends with a specific substring in JavaScript?
How do I check if a string starts with a specific substring in JavaScript?
How do I check if a string starts with a specific substring in JavaScript?
How do I check if a string ends with a specific substring in Python?
How do I check if a string contains a substring in JavaScript?
How do I check if a string contains a substring in JavaScript?
How do I check if a string starts with a specific substring in Python?
How do I check if an element has a specific class in JavaScript?
How do I check if a string is a palindrome in JavaScript?
How do I check if a string is empty in JavaScript?
How do I check if a variable is a string in JavaScript?
How do I check if an object has a specific property in JavaScript?
How do I check if a string is a valid URL in JavaScript?
How do I check if a string is a valid JSON in JavaScript?
How do I check if a value is a substring of a string in Python?
How do I check if an array contains a specific value in JavaScript?
How do I check if a value is an empty string in JavaScript?
How do I check if a value is an empty string in JavaScript?
How do I check if a value is an empty string in JavaScript without using length?
How can I check if an object has a specific property in JavaScript?