JavaScript String endsWith
Summary: in this tutorial, you will learn how to use the JavaScript String endsWith()
method to check if a string ends with a substring.
Introduction to the JavaScript String endsWith() method
The endsWith()
returns true
if a string ends with the characters of a specified string or false
otherwise.
Here’s the syntax of the endsWith()
method:
String.endsWith(searchString [,length])
Code language: CSS (css)
Arguments
searchString
is the characters to be searched for at the end of the string.length
is an optional parameter that determines the length of the string to search. It defaults to the length of the string.
Note that to check if a string starts with a substring, you use the startsWith()
method.
JavaScript String endsWith() method examples
Suppose that you have a string called title
:
const title = 'Jack and Jill Went Up the Hill';
Code language: JavaScript (javascript)
The following example uses the endsWith()
method to check if the title
ends with the string 'Hill'
:
console.log(title.endsWith('Hill'));
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
The endsWith()
method matches characters case-sensitively, therefore, the following example returns false
:
title.endsWith('hill');
Code language: JavaScript (javascript)
The following example uses the endsWith()
method with the second parameter that determines the length of the string to search:
console.log(title.endsWith('Up', 21));
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
Put it all together:
const title = 'Jack and Jill Went Up the Hill';console.log(title.endsWith('Hill'));
console.log(title.endsWith('hill'));
console.log(title.endsWith('Up', 21));
Code language: JavaScript (javascript)
Output:
true
false
true
Code language: JavaScript (javascript)
Summary
- Use the string
endsWith()
method to check if a string ends with a substring.