DEV Community

Cover image for Javascript Underrated Method "endsWith()"
Mahfuzur Rahman
Mahfuzur Rahman

Posted on

Javascript Underrated Method "endsWith()"

The endsWith function is a method available in JavaScript for strings. It is used to check if a string ends with a specified substring, and it returns a Boolean value (true or false) based on the result of the check.

Here's the basic syntax of the endsWith function:

string.endsWith("searchString", length]);
Enter fullscreen mode Exit fullscreen mode
  • string: The original string you want to check.

  • searchString: The substring you want to check for at the end of the original string.

  • length (optional): The length of the string to consider. If provided, endsWith will check if the substring appears within the first length characters of the original string.

The function returns true if the original string ends with the specified substring, and false otherwise.

Here are some examples:

const str = "Hello, world!";

console.log(str.endsWith("world"));  // true
console.log(str.endsWith("!"));      // true
console.log(str.endsWith("Hello"));   // false
console.log(str.endsWith("world", 7); // true (only considering the first 7 characters)

Enter fullscreen mode Exit fullscreen mode

In the first example, the string "Hello, world!" ends with "world," so endsWith returns true.
In the second example, it ends with "!" and returns true again.
In the third example, it does not end with "Hello," so it returns false.
The fourth example demonstrates the use of the optional length parameter, where we check if "world" appears within the first 7 characters of the string, which returns true.

Top comments (1)

Collapse
 
wolframkriesing profile image
Home Officer

Totally agree, it feels like endsWith() is "not seen" enough.
I also wrote a kata to learn (all details) about it jskatas.org/katas/es6/language/str...