DEV Community

Cover image for String.endsWith() in JavaScript
Moazam Ali
Moazam Ali

Posted on

String.endsWith() in JavaScript

The String.prototype.endsWith() method is a string method in JavaScript that returns a Boolean value indicating whether a string ends with a specified search string. This method is case-sensitive, meaning that it will return true only if the search string exactly matches the end of the target string.

Syntax

string.endsWith(searchValue, start)
Enter fullscreen mode Exit fullscreen mode
  • searchValue: A specified search string to be searched for at the end of the string.
  • start: The position within the string at which to begin searching for searchString. (Defaults to 0.)

It returns a boolean value, true if the searched string is found at the end of the given string; otherwise false if not found.

Here's an example of how to use the endsWith() method:

let str = 'Hello, world!';

console.log(str.endsWith('world!')); // Output: true
console.log(str.endsWith('World!')); // Output: false
Enter fullscreen mode Exit fullscreen mode

In this example, we create a string called str and use the endsWith() method to search for the substring 'world!' at the end of it. Since the search string exactly matches the end of the string str, the endsWith() method returns true. However, if we search for the string 'World!', which is not an exact match, the endsWith() method returns false.

The endsWith() method also accepts an optional second argument, which is the length of the substring to be searched within the target string. This is useful if you want to search for a substring within a specific part of the target string.

Here's an example of using the optional second argument:

let str = 'Hello, world!';
console.log(str.endsWith('world!', 12)); // Output: true
Enter fullscreen mode Exit fullscreen mode

In this example, we search for the substring 'world!' within the first 12 characters of the string str. Since the string 'world!' appears at the end of the first 12 characters of str, the endsWith() method returns true.

Wrapping up!

The endsWith() method is a convenient and easy way to search for substrings at the end of a string in JavaScript. It's often used in combination with other string methods, such as indexOf() and substr(), to perform more complex string operations.

That's all for this article, hope you learned something. Thanks for reading, catch you later.

You can also buy me a coffee that would help me grow as a frontend developer :)

Buy Me A Coffee


Top comments (0)