The String startsWith() method

By

Learn how the JavaScript startsWith() method checks whether a string starts with a given substring, and how a second argument sets where to start checking.

~~~

The startsWith() method checks if a string starts with the value of the string passed as parameter. It returns true or false.

You can call startsWith() on any string:

'testing'.startsWith('test') //true
'going on testing'.startsWith('test') //false

A common use case is checking the shape of a value before acting on it. For example, checking if a URL uses HTTPS:

const url = 'https://flaviocopes.com'
url.startsWith('https://') //true

Before this method existed, we did the same check with indexOf:

url.indexOf('https://') === 0 //true

It works, but startsWith() says what you mean. The method arrived with ES2015, so it’s available everywhere now.

The second parameter

This method accepts a second parameter, which lets you specify at which character you want to start checking:

'testing'.startsWith('test', 2) //false
'going on testing'.startsWith('test', 9) //true

In the second example, checking starts at index 9, right where testing begins in the string. From that position, the string does start with test.

A negative position is treated as 0, and a position past the end of the string always gives false.

One more edge case worth knowing: searching for the empty string always returns true, on any string. JavaScript considers every string to start with '':

'testing'.startsWith('') //true

The check is case sensitive

Here’s the pitfall that bites most often: startsWith() compares characters exactly, including their case.

'JavaScript'.startsWith('java') //false

If you’re matching user input or anything with unpredictable casing, normalize both sides first:

'JavaScript'.toLowerCase().startsWith('java') //true

You can’t pass a regular expression

The parameter must be a string. Passing a regex throws:

'testing'.startsWith(/test/)
//TypeError: First argument to String.prototype.startsWith must not be a regular expression

If you need pattern matching at the start of a string, use a regex with the ^ anchor and the test() method instead:

/^test/.test('testing') //true

Two siblings of startsWith() cover the other cases. endsWith() checks the end of the string, and includes() checks anywhere inside it:

'testing'.endsWith('ing') //true
'going on testing'.includes('on') //true

All three return a boolean and all three are case sensitive, so the same toLowerCase() trick applies.

~~~

Related posts about js: