The endsWith() method is useful for determining if the end of a string exactly matches another string.
The example below demonstrates a typical use case for the endsWith() method.
var StringOne = 'Hello World';
var StringTwo = 'World';
var TestResult = StringOne.endsWith(StringTwo);
if (TestResult){
document.write("The end of the string:\"" + StringOne + "\" is: \"" + StringTwo + "\"");
}else{
document.write("The end of the string:\"" + StringOne + "\" is not: \"" + StringTwo + "\"");
}
//The end of the string:"Hello World" is: "World"
StringTwo = 'Earth';
TestResult = StringOne.endsWith(StringTwo);
if (TestResult){
document.write("The end of the string:\"" + StringOne + "\" is: \"" + StringTwo + "\"");
}else{
document.write("The end of the string:\"" + StringOne + "\" is not: \"" + StringTwo + "\"");
}
//The end of the string:"Hello World" is: "Earth"
Specifying the Length of a String When Using endsWith()
The endsWith() method can also be passed a second argument, the length of the expected string.
As demonstrated in the example below, the length passed to endsWith() can be smaller than the length of the string.
var StringOne = 'Hello World';
var StringTwo = 'World';
var TestResult = StringOne.endsWith(StringTwo,5);
if (TestResult){
document.write("The end of the string:\"" + StringOne.substring(0,5) + "\" is: \"" + StringTwo + "\"");
}else{
document.write("The end of the string:\"" + StringOne.substring(0,5) + "\" is not: \"" + StringTwo + "\"");
}
//The end of the string:"Hello" is not: "World"
Alternative to the endsWith() Method
An alternative way to check the contents of the end of a string can be done with the substring() method.
As you can see in the example below; Using substring() takes a lot more code, but it is more flexible and can be used in many more situations.
var MyString = "Bob says Hello World";
var AnotherString = "World";
var SubString = MyString.substring(MyString.length - AnotherString.length,MyString.length);
if (AnotherString == SubString){
document.write("The String:\"" + MyString + "\" contains :\"" + AnotherString + "\"");
}else{
document.write("The String:\"" + MyString + "\" does not contain :\"" + AnotherString + "\"");
}
//The String:"Bob says Hello World" contains :"World"