JavaScript - String endsWith() method example

3 points
Created by:

The method checks if string ends with some text.

// ONLINE-RUNNER:browser;

const text = 'ABC';

console.log(text.endsWith('C'));  // true
console.log(text.endsWith('BC')); // true


1. Documentation


String endsWith(searchString)

String endsWith(searchString, endPosition)

Typed syntaxString endsWith(searchString: string, endPosition?: number): boolean

searchString - text searched for at the end of the string

endPosition (optional) - indicates the part of the string that we want to test (by default this.length)

ResultReturns true if the given text was found at the end of the string, otherwise returns false.

The endsWith() is non-static method that checks whether a string ends with the text of a specified string, returning true or false. When we use endPosition paramter the metod cuts search area to endPosition (it is treat as the string length).

Warning: intoduced in ES2015.

2. Practical example

Example 1

// ONLINE-RUNNER:browser;

const text = 'Some text ...';

console.log(text.endsWith('...'));       // true
console.log(text.endsWith('text ...'));  // true

console.log(text.endsWith('Some'));      // false
console.log(text.endsWith('Some text')); // false

Example 2 - with optional endPosition character

// ONLINE-RUNNER:browser;

// endPosition:   4    9
//                |    |
//                v    v
const text = 'Some text ...';

console.log(text.endsWith('Some', 4));  // true 
console.log(text.endsWith('text', 9));  // true
console.log(text.endsWith('Some', 9));  // false   // 'Some text' doesn't end with 'Some'

console.log(text.endsWith('text ...', text.length));  // true



  1. String.prototype.endsWith() - JavaScript | MDN

Alternative titles

  1. JavaScript - String.prototype.endsWith() documentation with examples
  2. js - String endsWith() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (documentation)

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂