What is endsWith() Method in JavaScript ?
In JavaScript, the endsWith()
method is used to determine whether a string ends with a specified suffix (another string). It returns true
if the string ends with the specified suffix, and false
otherwise.
Syntax:
string.endsWith(suffix, length)
string
: The string to be checked.suffix
: The string to be searched for at the end ofstring
.length
(optional): The length of the portion of the string to consider. If provided, only the characters up to the specified length will be considered for the search. Default is the entire length of the string.
Example: Here, the endsWith()
method is called on the str
string to check if it ends with the suffix “World!”. Since “World!” is present at the end of the string, the method returns true
, which is then assigned to the variable endsWithWorld
.
Javascript
const str = "Hello, World!" ; const endsWithWorld = str.endsWith( "World!" ); console.log(endsWithWorld); // Output: true |
Output
true
Note:
- The
endsWith()
method is case-sensitive. It matches the suffix exactly, including case, when searching. - If the string ends with the specified suffix,
endsWith()
returnstrue
; otherwise, it returnsfalse
. - The
length
parameter allows you to specify the length of the portion of the string to consider for the search. This can be useful if you only want to check a specific part of the string for the suffix.
Contact Us