Javascript String endsWith()

Introduction

Javascript String endsWith() searches a string for a given substring and return a boolean indicating whether it is included.

endsWith() checks for a match beginning at index (string.length - substring.length).

str.endsWith(searchString[, length])
  • searchString - the characters to be searched for at the end of str.
  • length - Optional, used as the length of str. Defaults to str.length.
let message = "foobarbaz"; 
console.log(message.endsWith("baz"));    // true 
console.log(message.endsWith("bar"));    // false 

The endsWith() method accepts an optional second argument that indicates the position that should be treated as the end of the string.

If this value is not provided, the length of the string is used by default.

When a second argument is provided, the method will treat the string as if it only has that many characters:

let message = "foobarbaz"; 

console.log(message.endsWith("bar"));     // false 
console.log(message.endsWith("bar", 6));  // true 



PreviousNext

Related