JavaScript String endsWith() Tutorial

In this section, we will learn what the endsWith() method is and how to use it.

JavaScript String endsWith() Method

The endsWith() method is used to check whether a string value ends with a specific value.

For example, let’s say you have a string that is “This is a simple sentence”; now we want to know if that sentence ends with “sentence”. With the help of this method, we can easily do that.

JavaScript String endsWith() Syntax

string.endsWith(searchvalue, length)

String endsWith() Method Parameters:

The method takes two arguments:

  • The first argument is the characters in which we want to know if the target string ends with those characters.
  • The second argument, which is optional, declares the length of the target string. For example, if the target string is 200 characters long, we can limit the length of the string via this second argument to something like 100. This means now the end of the string is considered at the index number 99.

String endsWith() Method Return Value:

The return value of this method is either `true` or `false`.

If the value is `true` that means the characters that we set as the argument matched the end of the target string.

If the characters didn’t match the end of the target string, we will get the value `false`.

Example: using String endsWith() method in JavaScript

const str = "John Doe is the best developer in the world!";

console.log(str.endsWith("world!"));

console.log(str.endsWith("globe!"));

Output:

true

false
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies