JavaScript endswith() method
The endsWith()
method in JavaScript is used to determine whether a string ends with a specified substring (search string). It returns a boolean value (true
or false
) based on whether the string concludes with the specified substring.
Syntax:
searchString
: The substring you want to check for at the end of the string.length
(optional): An integer that specifies the length of the string to consider for the search. If provided, the search will only consider the substring from the start of the string up to the specified length. If omitted, the entire string is considered.
Return Value:
- It returns
true
if the string ends with the specifiedsearchString
; otherwise, it returnsfalse
.
Example 1: Basic Usage
In this example, the string "document.pdf"
indeed ends with the substring ".pdf"
, so endsWith()
returns true
.
Example 2: Case Sensitivity
The endsWith()
method is case-sensitive. This means that "Hello"
and "hello"
are treated as different strings.
Example 3: Specifying the Length
You can specify the length to limit the portion of the string that is considered for the search. The search will only look at the characters from the start of the string up to the specified length
.
Example 4: Handling Empty Strings
If you check for an empty string, the endsWith()
method will always return true
, as any string ends with an empty substring.
Example 5: Not Finding the Substring
If the searchString
is not found at the end of the original string, the method will return false
.
Summary:
- The
endsWith()
method checks if a string ends with a specified substring and returnstrue
orfalse
. - It is case-sensitive and can accept an optional second argument to specify the length of the string to consider.
- The method returns
true
for an empty search string since every string ends with an empty substring. - This method is useful for validating file extensions, URL paths, and other string patterns at the end of a string.