The endsWith() method of the String class in JavaScript determines whether a string ends with the characters of the specified string, searchString. It can also check within a specific portion of the string by providing an endPosition parameter.
There are 2 variations for the syntax of String.endsWith() method. They are:
endsWith(searchString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for at the end of this string. |
This method determines whether a string ends with the characters of the string searchString.
Returns value of type Boolean
.
endsWith(searchString, endPosition)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for at the end of this string. |
endPosition | optional | The position within the string at which to end the search. Defaults to the string's length. |
This method determines whether a string ends with the characters of the string searchString, considering only the portion of the string up to endPosition.
Returns value of type Boolean
.
In JavaScript, we can use the endsWith()
method to check if a string ends with a specified substring.
For example,
str
with the value 'Hello, world!'
.endsWith()
method with the argument 'world!'
to check if the string ends with 'world!'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.endsWith('world!');
console.log(result);
true
In JavaScript, we can use the endsWith()
method to check if a string ends with a specified substring, up to a certain position.
For example,
str
with the value 'Hello, world!'
.endsWith()
method with the arguments 'Hello'
and 5
to check if the substring from the start to position 5
ends with 'Hello'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.endsWith('Hello', 5);
console.log(result);
true
In JavaScript, we can use the endsWith()
method to demonstrate a case where the string does not end with the specified substring.
For example,
str
with the value 'Hello, world!'
.endsWith()
method with the argument 'Hello'
to check if the string ends with 'Hello'
.result
.result
to the console using the console.log()
method.const str = 'Hello, world!';
const result = str.endsWith('Hello');
console.log(result);
false
In this JavaScript tutorial, we learned about endsWith() method of String: the syntax and few working examples with output and detailed explanation for each example.