Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
string
communitycreator

How to find if a string endsWith a specific string in JavaScript

Programming Bytes

Using endsWith

We can use the endsWith method of the String object to check if a string ends with the specified substring.

let lifeStr = "Life-Dead";
lifeStr.endsWith("Dead"); // true

The endsWith method returns true if a string ends with the passed substring.

The endsWith method takes two arguments:

  • searchString - String to be searched for at the end of source string.
  • endPosition - Optional argument specifies the position up to which the string will be tested. The default value is the length of the string.

Example

let testStr = "JavaScript is good";
let subStr = "d";
console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr) ); // true

subStr = "good";
console.log(`\nChekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr) ); // true

subStr = "bad";
console.log(`\nChekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr) ); // true

In the code above, we have checked 3 case. If “JavaScript is good”, the String:

  • Ends with d - true
  • Ends with good - true
  • Ends with bad - false

The endsWith method is case sensitive.

let testStr = "JavaScript is good";
testStr.endsWith("D"); //false

In the example above, the testStr variable ends with d, not D.


We can also specify the end position (index - 1 = position) of the string.

var testStr = "JAVASCRIPT";
let subStr = "VA";
let endPosition = 4;
console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr, endPosition) ); // true

subStr = "AVA";
console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr, endPosition) ); // true

subStr = "EVA";
console.log(`Chekcing if '${testStr}' endsWith '${subStr}'`,  testStr.endsWith(subStr, endPosition) ); // true

In the code above, we have passed the end position as 4 to endsWith method; so, the string will only be searched until the 4th positiononly searched until “JAVA.

RELATED TAGS

javascript
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring