Uncover the Power of JavaScript’s endsWith() Method
When working with strings in JavaScript, understanding how to effectively manipulate and search them is crucial. One often overlooked yet powerful tool in your arsenal is the endsWith()
method.
What is the endsWith() Method?
The endsWith()
method is a built-in JavaScript function that allows 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.
Example 1: Basic Usage
Let’s demonstrate the endsWith()
method in action:
const sentence = "JavaScript is fun";
console.log(sentence.endsWith("fun")); // true
console.log(sentence.endsWith("is")); // false
Example 2: Case Sensitive Search
Here’s an example showcasing the case sensitivity of the endsWith()
method:
const sentence = "JavaScript is fun";
console.log(sentence.endsWith("fun")); // true
console.log(sentence.endsWith("Fun")); // false
Example 3: endsWith() with Two Parameters
In this example, we’ll specify the portion of the string to consider while searching for the searchString
:
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.