Unlocking the Potential of JavaScript’s endsWith() Method

What is the endsWith() Method?

The endsWith() method is a built-in JavaScript function that enables you to determine if a string ends with a specified set of characters. This method takes two parameters: searchString and length. The searchString parameter specifies the characters to be searched for at the end of the string, while the length parameter (optional) defines the portion of the string to consider.

How Does the endsWith() Method Work?

The endsWith() method returns a boolean value indicating whether the string ends with the specified searchString. If the string ends with the searchString, the method returns true; otherwise, it returns false.

Case Sensitivity Matters

It’s essential to note that the endsWith() method is case sensitive. This means that “fun” and “Fun” are treated as two distinct strings. If you’re searching for a string with a specific case, make sure to match it exactly.

Examples

Example 1: Basic Usage

const sentence = "JavaScript is fun";
console.log(sentence.endsWith("fun")); // true
console.log(sentence.endsWith("is")); // false

Example 2: Case Sensitive Search

const sentence = "JavaScript is fun";
console.log(sentence.endsWith("fun")); // true
console.log(sentence.endsWith("Fun")); // false

Example 3: endsWith() with Two Parameters

const sentence = "JavaScript is fun";
console.log(sentence.endsWith("JavaScript", 10)); // true

By leveraging the endsWith() method, you can simplify your string manipulation tasks and write more efficient code. Remember to keep case sensitivity in mind and explore the various ways to utilize this powerful method in your JavaScript projects.

Leave a Reply