String.endsWith() in JavaScript
Moazam Ali
Posted on January 10, 2023
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)
- 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 to0
.)
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
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
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 :)
Posted on January 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.