How to check if a string starts with another in JavaScript
By Flavio Copes
Learn how to check if a string starts with another in JavaScript using the startsWith() method, including its optional position parameter to start later.
To check if a string starts with another string, use the startsWith() method. ES6, introduced in 2015, added it to the String object prototype.
This is the way to perform this check in modern JavaScript.
This means you can call startsWith() on any string, provide a substring, and check if the result returns true or false:
'testing'.startsWith('test') //true
'going on testing'.startsWith('test') //false
Note that it returns a boolean, not a position. That makes it perfect inside an if:
const url = 'https://flaviocopes.com/javascript/'
if (url.startsWith('https://')) {
console.log('secure link')
}
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 first example, starting at index 2 means we’re checking if 'sting' starts with 'test'. It doesn’t, so we get false.
In the second one, index 9 lands right on the t of testing, so the check passes.
I rarely reach for this parameter, but it’s handy when you already know the position of something in the string and want to check what comes after it.
Watch out: the check is case sensitive
Here’s the pitfall that catches people. startsWith() compares characters exactly, so casing matters:
'Testing'.startsWith('test') //false
If you want a case insensitive check, lowercase both sides first:
'Testing'.toLowerCase().startsWith('test') //true
This comes up a lot with user input. Someone types HTTPS:// in uppercase and your startsWith('https://') check fails. Normalize the string before checking.
What did we do before ES6?
Before startsWith() existed, the common trick was indexOf():
'testing'.indexOf('test') === 0 //true
indexOf() returns the position of the first match, so a result of 0 means the string starts with it. It works, but the intent is much less obvious than startsWith().
You’ll still find this pattern in older codebases. There’s no reason to write it today: startsWith() is supported in every modern browser and in Node.js, so unless you need to support very old browsers without transpiling, use it and keep the code readable.
Related posts about js: