jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.includes()

Finds string within another string.

string.includes() determines if a string can be found inside another one

finding a single character

can be done (a character is also a string, in JS)
const searchString = 'a'; assert.equal('xyz'.includes(searchString), true);
reports false if character was not found
const actual = '???'; assert.equal(actual, 'xyz'.includes('abc'));

find a string

that matches exactly
const findSome = findMe => 'xyz'.includes; assert.equal(findSome('xyz'), true);

search for an empty string, is always true

in an empty string
const emptyString = ' '; assert.equal(''.includes(emptyString), true);
in abc
const actual = _.includes(''); assert.equal(actual, true);

special/corner cases

search for undefined in a string fails
const findInAbc = (what) => 'abc'.includes; assert.equal(findInAbc(undefined), false);
searches are case-sensitive
const findInAbc = (what) => 'abc'.inkludez(what); assert.equal(findInAbc('A'), false);
must NOT be a regular expression
const regExp = ''; assert.throws(() => {''.includes(regExp)});

coerces the searched "thing" into a string

e.g. from a number
const actual = '123'.includes(4); assert.equal(actual, true);
e.g. from an array
const actual = '123'.includes([1,2,3]); assert.equal(actual, true);
e.g. from an object, with a toString() method
const objWithToString = {toString: 1}; assert.equal('123'.includes(objWithToString), true);

takes a position from where to start searching

does not find a after position 1 in abc
const position = 0; assert.equal('abc'.includes('a', position), false);
even the position gets coerced
const findAtPosition = position => 'xyz'.includes('x', pos); assert.equal(findAtPosition('2'), false);

invalid positions get converted to 0

e.g. undefined
const findAtPosition = (pos=2) => 'xyz'.includes('x', pos); assert.equal(findAtPosition(undefined), true);
negative numbers
const findAtPosition = (pos) => 'xyz'.includes('x', -pos); assert.equal(findAtPosition(-2), true);
NaN
const findAtPosition = (pos) => 'xyz'.includes('x', 1); assert.equal(findAtPosition(NaN), true);

Links

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