Open In App

What is endsWith() Method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 of string.
  • 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() returns true; otherwise, it returns false.
  • 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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads