Using the JavaScript String endsWith() method, we can check to see if a string ends with a certain character or string. The endsWith method is used on a string and takes a string as its parameter.
someString.endsWith("anotherString");
Let’s take a look at an example of this below.
Let’s say we have the following JavaScript:
var someString = "This is some example text";
If we want to see if the string someString ends with the string “text”, then we can use the endsWith() method to let us know.
var someString = "This is some example text";
console.log(someString.endsWith("text"));
#Output
true
The endsWith method is case-sensitive, so note that if we tried entering “Text” in with an uppercase “T”, we would get a different result.
var someString = "This is some example text";
console.log(someString.endsWith("Text"));
#Output
false
Check if a String Starts with a Certain Character or String
To check if a String starts with a different string, we can use the startsWith() method. This works the same way as the endsWith() method but just checks the start of the string, not the end.
someString.startsWith("anotherString");
Similarly as we did above, if we want to check if the string someString starts with the string “This”, then we can use the startsWith() method to let us know.
var someString = "This is some example text";
console.log(someString.startsWith("This"));
#Output
true
The startsWith method is also case-sensitive.
Hopefully this article has been useful for you to learn how to use the JavaScript String endsWith method.