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 [,endPosition])
Code language: JavaScript (javascript)
In this syntax:
searchString
is the characters to be searched for at the end of the string.endPosition
is an optional parameter that determines the end position at whichsearchString
is expected to be found. TheendPosition
defaults to the length of the input string.
The endsWith()
method always performs a case-sensitive search when matching strings.
Note that to check if a string starts with a substring, you use the startsWith()
method.
JavaScript String endsWith() method examples
Let’s take some examples of using the JavaScript string endsWith()
method.
Basic JavaScript String endsWith() method example
The following example uses the endsWith()
method to check if the string "JavaScript is awesome"
ends with the substring"Awesome"
:
const s = "JavaScript is awesome";
const result = s.endsWith("awesome");
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: true }
Code language: CSS (css)
The endsWith()
method matches characters case-sensitively, therefore, the following example returns false
:
const s = "JavaScript is awesome";
const result = s.endsWith("Awesome");
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: false }
Code language: CSS (css)
Using the second parameter example
The following example uses the endsWith()
method with the second parameter (endPosition
) that determines end position in the input string to match:
const s = "JavaScript is awesome";
const result = s.endsWith("Script", 10);
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: true }
Code language: CSS (css)
In this example, we specify the endPosition
is 10, so the JavaScript
string ends with the Script
string.
Summary
- Use JavaScript string
endsWith()
method to check if a string ends with a substring.