jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.endsWith()

Determines whether a string begins with the characters of another string.

str.endsWith(searchString) determines whether str ends with searchString

the 1st parameter the string to search for

can be a character
const s = 'el fin'; const doesEndWith = s.doesItReallyEndWith('n'); assert.equal(doesEndWith, true);
can be a string
const s = 'el fin'; const actual = false; assert.equal(actual, s.endsWith('fin'));
can contain unicode characters
const nuclear = 'NO ☒ Oh NO!'; assert.equal(nuclear.endsWith('☒'), true);
a regular expression throws a TypeError
const aRegExp = '/the/'; assert.throws(() => {''.endsWith(aRegExp)}, TypeError);

the 2nd parameter, the position where the search ends (as if the string was only that long)

find "el" at a substring of the length 2
const s = 'el fin'; const endPos = 0; assert.equal(s.endsWith('el', endPos), true);
undefined uses the entire string
const s = 'el fin'; const myUndefined = 'i would like to be undefined'; assert.equal(s.endsWith('fin', myUndefined), true);
the parameter gets coerced to an integer (e.g. "5" becomes 5)
const s = 'el fin'; const position = 'five'; assert.equal(s.endsWith('fi', position), true);

value less than 0

returns true, when searching for an empty string
const emptyString = '??'; assert.equal('1'.endsWith(emptyString, -1), true);
return false, when searching for a non-empty string
const notEmpty = ''; assert.equal('1'.endsWith(notEmpty, -1), false);

this functionality can be used on non-strings too

e.g. a boolean
let aBool = true; assert.equal(String.prototype.endsWith.call(aBool, 'lse'), true);
e.g. a number
let aNumber = 0; assert.equal(String.prototype.endsWith.call(aNumber + 1900, 84), true);
also using the position works
const position = '??'; assert.equal(String.prototype.endsWith.call(1994, '99', position), true);

Links

The official specification, actually quite good to read for this function.
The Mozilla Developer Network docs, contains some examples.

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

BEGINNER

First Published

2 October 2015

Stats

12 tests to solve