JavaScript(JS) string method - endswith
The endsWith()
method is a string method in JavaScript that is used to check whether a given string ends with a specified substring or not.
Here is the syntax for the endsWith()
method:
str.endsWith(searchString[, length])
Here, str
is the original string you want to search in, and searchString
is the substring you want to search for at the end of the str
. The optional length
parameter specifies the length of the string to search, and if not specified, it searches the entire string.
The endsWith()
method returns a boolean value true
if the string ends with the specified substring, and false
otherwise.
Here is an example of using endsWith()
method:
let str = "Hello World"; console.log(str.endsWith("World")); // true console.log(str.endsWith("o")); // false console.log(str.endsWith("o", 5)); // true
In the first console.log()
, the endsWith()
method returns true
because the str
ends with the substring "World". In the second console.log()
, it returns false
because the str
does not end with the substring "o". In the third console.log()
, it returns true
because the str
ends with the substring "o" within the first five characters of the string.