When working with JavaScript, there are often situations where we need to check if a string ends with a specific substring. This can be useful in various scenarios, such as validating input or manipulating data. In this blog post, we will explore different ways to achieve this using JavaScript.
Using the endsWith() Method
One of the easiest and most straightforward ways to check if a string ends with a specific substring is by using the built-in endsWith()
method. This method returns true
if the string ends with the specified substring, and false
otherwise.
const str = "Hello, World!";
const endsWithWorld = str.endsWith("World!");
console.log(endsWithWorld); // Output: true
In the above example, we have a string "Hello, World!"
and we want to check if it ends with "World!"
. By calling endsWith("World!")
on the string, we get the desired result of true
.
Using Regular Expressions
Another way to check if a string ends with a specific substring is by using regular expressions. Regular expressions provide powerful pattern matching capabilities, allowing us to match and manipulate strings based on specific patterns.
const str = "Hello, World!";
const endsWithWorld = /World!$/.test(str);
console.log(endsWithWorld); // Output: true
In the above example, we use the regular expression /World!$/
to check if the string ends with "World!"
. The $
symbol represents the end of the string, so the regular expression will only match if the substring is found at the end.
Using substring() and lastIndexOf()
If you prefer a more manual approach, you can also use the substring()
and lastIndexOf()
methods to check if a string ends with a specific substring.
const str = "Hello, World!";
const endsWithWorld = str.substring(str.lastIndexOf("World!")) === "World!";
console.log(endsWithWorld); // Output: true
In this example, we first use lastIndexOf("World!")
to find the index of the last occurrence of the substring in the string. Then, we use substring()
to extract the substring starting from that index. Finally, we compare the extracted substring with the desired substring to determine if the string ends with it.
These are three different approaches you can use to check if a string ends with a specific substring in JavaScript. Choose the one that best suits your needs and coding style.
Leave a Reply