Sometimes we have to check whether a JavaScript string starts with a given substring.
In this article, we’ll look at how to check if a JavaScript string starts with another string.
String.prototype.startsWith
ES6 added the startsWith method to a string.
For instance, we can write:
console.log("hello world".startsWith("hello"));
We call startsWith on the string and we pass in the substring that we want to check whether the 'hello world' string starts with it.
The console log should show true since 'hello world' starts with 'hello' .
String.prototype.substring
Another way to check if a string starts with the given substring is to use the substring method.
It takes the start and end index as the argument.
And it returns the substring beginning with the starting index to the end index minus 1.
Therefore, we can write:
const data = 'hello world'
const input = 'hello'
console.log(data.substring(0, input.length) === input)
data is the full string.
substring has arguments 0 and input.length to extract the substring from index 0 to input.length — 1 .
So subtring should return 'hello' , which is the same as input .
Regex Test
We can search for a given pattern with JavaScript regex object’s test method.
And we can check whether a string begins with a given substring by using the ^ symbol to start searching for a pattern at the beginning of a string.
For instance, we can write:
console.log(/^hello/.test('hello world'))
to check whether 'hello world' starts with hello .
Equivalently, we can use the RegExp constructor to create the regex object:
console.log(new RegExp('^hello').test('hello world'))
This lets us pass in a regex string to create the regex object instead of creating a regex literal.
So it’s handy for creating regex objects dynamically.
String.prototype.lastIndexOf
A JavaScript string also comes with the lastIndexOf method to check the last index of a given substring in a string.
To use it to check whether a string starts with a given substring, we can write:
console.log('hello world'.lastIndexOf('hello', 0) === 0)
We call lastIndexOf with the substring we’re searching for like the first argument.
The 2nd argument is the index that we start searching for the substring from.
If it returns 0, then we know the substring is located in index 0 and starts there.
String.prototype.indexOf
We can replace lastIndexOf with indexOf to get the same behavior.
Instead of searching for the last instance of a substring with lastIndexOf .
We can search for the search instance of a substring with indexOf .
It makes no difference to us since we just want to know if a string starts with a given substring.
For instance, we can write:
console.log('hello world'.indexOf('hello', 0) === 0)
to do the check.
Conclusion
There are many JavaScript string methods we can use to check whether a string starts with the given substring.