Home » Programming » Javascript » Javascript Endswith

The endsWith() Method for JavaScript Strings, with Examples

The endsWith() String method in JavaScript will determine whether a string ends with a certain string or character. Here’s how to use it, with examples.

endsWith() Method JavaScript Syntax

The endsWith() method can be called from any String variable.

string.endsWith(SEARCH, LENGTH)

Note that:

  • string can be any string value or variable
  • SEARCH should be the string which you want to check if string ends with
  • LENGTH is OPTIONAL
    • If specified, LENGTH will be used as the length of the STRING being checked
    • If it is less than the actual length of string, the rest of the string beyond LENGTH will be ignored
      • This can be useful if you want to check whether a string exists at a certain position within a string
  • A boolean value of TRUE (if the string ends with the given value) or FALSE is returned

endsWith() Examples

The below examples show how the endsWith method is used. A string variable named test is declared, and the endswith() method is called on it.

let test = 'Beam me up, Scotty.'

test.endsWith('Scotty.');  // true
test.endsWith('up');       // false
test.endsWith('up', 10);   // true

Note the last example supplies a length, so that only a portion of the string is used.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment