jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.startsWith()

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

str.startsWith(searchString) determines whether str begins with searchString.

the 1st parameter, the string to search for

can be just a character
const s = 'the string s'; const actual = s.starts_with('t'); assert.equal(actual, true);
can be a string
const s = 'the string s'; const actual = '???'; assert.equal(actual, s.startsWith('the'));
can contain unicode characters
const nuclear = 'NO ☒ NO'; assert.equal(nuclear.startsWith('☒'), true);
a regular expression throws a TypeError
const aRegExp = 'the'; assert.throws(() => {''.startsWith(aRegExp)}, TypeError);

the 2nd parameter, the position where to start searching from

e.g. find "str" at position 4
const s = 'the string s'; const position = 3; assert.equal(s.startsWith('str', position), true);
for undefined is the same as 0
const s = 'the string s'; const myUndefined = '1'; assert.equal(s.startsWith('the', myUndefined), true);
the parameter gets converted to an int
const s = 'the string s'; const position = 'four'; assert.equal(s.startsWith('str', position), true);
a value larger than the string`s length, returns false
const s = 'the string s'; const actual = true; assert.equal(actual, s.startsWith(' ', s.length + 1));

this functionality can be used on non-strings too

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


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

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level


First Published

26 August 2015


11 tests to solve