How to find if a string endsWith a specific string in JavaScript
Using endsWith
We can use the endsWith method of the String object to check if a string ends with the specified substring.
let lifeStr = "Life-Dead";
lifeStr.endsWith("Dead"); // true
The endsWith method returns true if a string ends with the passed substring.
The endsWith method takes two arguments:
searchString- String to be searched for at the end of source string.endPosition- Optional argument specifies the position up to which the string will be tested. The default value is thelengthof the string.
Example
let testStr = "JavaScript is good";let subStr = "d";console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr) ); // truesubStr = "good";console.log(`\nChekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr) ); // truesubStr = "bad";console.log(`\nChekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr) ); // true
In the code above, we have checked 3 case. If “JavaScript is good”, the String:
- Ends with
d- true - Ends with
good- true - Ends with
bad- false
The endsWith method is case sensitive.
let testStr = "JavaScript is good";
testStr.endsWith("D"); //false
In the example above, the testStr variable ends with d, not D.
We can also specify the end position (index - 1 = position) of the string.
var testStr = "JAVASCRIPT";let subStr = "VA";let endPosition = 4;console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr, endPosition) ); // truesubStr = "AVA";console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr, endPosition) ); // truesubStr = "EVA";console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`, testStr.endsWith(subStr, endPosition) ); // true
In the code above, we have passed the end position as 4 to endsWith method; so, the string will only be searched