How to check if a string ends with another string or character in JavaScript

JavaScript endsWith method, check if string ends with another string or character:

In this post, we will learn how to use endsWith method of JavaScript string. This method can be used to check if a string ends with a character or another substring or not.

It returns one boolean value based on the check.

Let’s learn the definition of this method first.

Definition of endsWith:

The endsWith method is defined as like below:

endsWith(str, l)

Here,

  • The first parameter is the string that we are searching in the string. We can pass a single character or characters/string. These characters will be searched at the end of the string.
  • The second parameter is the length of the string. It is an optional value. If we don’t provide this value, the string length is used here.

Return value of endsWith:

It returns a boolean value. It returns true if the characters are found in the end of the string. Else, it returns false.

Example of endsWith with characters:

Let’s take an example of endsWith with characters:

const givenStr = "Hello World";

console.log(givenStr.endsWith("d"));
console.log(givenStr.endsWith("a"));
console.log(givenStr.endsWith(""));

It is trying endsWith with the string givenStr with three different characters: ‘d’, ‘a’, ”. If you run this program, it will print true for ‘d’ and for the empty string.

true
false
true

JavaScript endsWith example program

Example of endsWith method with string:

Let’s try it with strings:

const givenStr = "Hello World";

console.log(givenStr.endsWith("rld"));
console.log(givenStr.endsWith("World"));
console.log(givenStr.endsWith(" World"));

It will print true for all of these three because all of these three words are at the end of givenStr.

Example of endsWith method with both parameters:

Let’s try endsWith method with both parameter values:

const givenStr = "Hello World";

console.log(givenStr.endsWith("World", 20));
console.log(givenStr.endsWith("World", 6));
console.log(givenStr.endsWith("llo ", 6));
console.log(givenStr.endsWith("World", 11));
  • For the first one, it will find the word from the end of the string because 20 is greater than the string length.
  • For the second one, it will find the word from end starting from the index 5 of the string.
  • For the third one, it will find the word from the end starting from the index 5 of the string.
  • For the last one, it will find the word from the end starting from the index 10.

It will print:

true
false
true
true

You might also like: