The syntax of the endsWith()
method is:
str.endsWith(searchString, length)
Here, str is a string.
endsWith() Parameters
The endsWith()
method takes in :
- searchString - The characters to be searched for at the end of str.
- length (optional) - It is used as the length of str where searchString is searched. Default value is
str.length
.
Return value from endsWith()
- Returns
true
if the given characters are found at the end of the string. - Returns
false
if given characters are not found at the end of the string.
Note: The endsWith()
method is case sensitive.
Example: Using endsWith() method
sentence = "Java is to JavaScript what Car is to Carpet.";
let check = sentence.endsWith("to Carpet.");
console.log(check); // true
let check1 = sentence.endsWith(".");
console.log(check1); // true
// case sensitive
let check2 = sentence.endsWith("carpet.");
console.log(check2); // false
// second argument specifies the portion of string to consider
let check3 = sentence.endsWith("JavaScript", 21);
console.log(check3); // true
Output
true true false true
Recommended Reading: JavaScript String startsWith()