What is the String endsWith() method in JavaScript?
Overview
The String endsWith() method in JavaScript is used to check whether a string ends with a specified string.
Syntax
The endsWith() method can be declared as shown in the code snippet below:
str.endsWith(str2, len)
Parameter
-
str: The string which is to be checked if its ends withstr2. -
str2: The string to be searched at the end ofstr. -
len: The number of characters ofstrto be searched. It is optional.
If the value of
stris not provided, its default value is used. The default value oflenis equal to the length ofstr.
Return value
The endsWith() method returns boolean such that:
-
The return value is
trueifstrends withstr2. -
The return value is
falseifstrdoes not end withstr2.
Browser compatibility
The endsWith() method is supported by the following browsers:
- Chrome 41
- Edge 12
- Firefox 17
- Opera 28
- Safari 9
Code
Consider the code snippet below, which demonstrates the use of the endsWith() method:
let str = 'This is Educative. This is endsWith() example code.'console.log(str.endsWith('code.'))console.log(str.endsWith('code.', 10))console.log(str.endsWith('example.'))
Explanation
A string str is declared in line 1.
-
The
endsWith()method is used in line 3 to check isstrends with the string'code.'. TheendsWith()method returnstrue. -
The
endsWith()method is used in line 4 to check isstrends with the string'code.'.The parameter
lenpassed to theendsWith()method is10. This means that only first 10 characters ofstrwill be searched to find the string'code'at the end.The
endsWith()method returnsfalse. This is because the end of first 10 characters ofstris not equal to the stringcode. -
The
endsWith()method is used in line 5 to check isstrends with the string'example.'. TheendsWith()method returnsfalse.