How to Use the JavaScript endsWith() Method with a Length Parameter?

Estimated read time 1 min read

The endsWith() method in JavaScript is used to check if a string ends with a specified suffix. The endsWith() method has two parameters: the suffix to search for, and an optional length parameter that indicates the number of characters to consider in the string.

Here’s an example of how to use the endsWith() method with the length parameter:

var str = "Hello, world!";
var suffix = "world!";
var len = 5;

console.log(str.endsWith(suffix, len)); // outputs: false

In this example, the endsWith() method checks if the string str ends with the suffix "world!", but only considers the first 5 characters of the string. Since the first 5 characters of the string are "Hello", the method returns false.

The length parameter is useful when you want to check if the end of a string matches a suffix, but only consider a portion of the string. By specifying the length parameter, you can limit the number of characters that the endsWith() method considers in its comparison.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply