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
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:
- 6 different ways in JavaScript to print the content of an array
- JavaScript array values() function
- 3 ways to get a random value from an array in JavaScript
- 4 ways in JavaScript to check if a string starts with a number
- How to check if an object is null or undefined in JavaScript
- 4 JavaScript program to check if the first character of a string is in lower case or not
- 4 ways in JavaScript to check if the first character of a string is in upper case
- How to use JavaScript string lastIndexOf method
- How to use the substring method in JavaScript string