Tuesday, 6 April, 2021 UTC


Summary

Introduction

In this tutorial, we'll take a look at how to check if a string starts with a substring in JavaScript.
This is easily achieved either through the startsWith() method, or regular expressions.

Check if String Starts with Another String with startsWith()

The startsWith(searchString[, position]) method returns a boolean which indicates whether a string begins with the characters of a specified searchString. Optionally we can also use the position argument to specify the position of the string at which to begin searching.
Let's see this in action:
const str = "This is an example for startsWith() method";

console.log(str.startsWith("This")); // true
console.log(str.startsWith("is", 2)); // true
In the first example, we are checking if the string str starts with "This".
In the second example, we are checking if str starts with "is", if we are starting our search from index 2 (i.e, 3rd character).

Check if String Starts with Another String with Regular Expressions

Regular Expressions are really powerful, and allow us to match various patterns. This is a great use-case for them, since we're essentially checking for a pattern - if a string starts with a substring.
The regexObj.test(reg) method tries to match the specified regular expression reg to the original string and returns a boolean value which indicates if a match was found:
const str = "hello world";

const regEx = /^he/;

console.log(regEx.test(str)); // true
In this approach, we are checking whether the pattern regEx occurs in the string str. The ^ metacharacter represents that the specified pattern he must be at the start of a line. Thus, the regular expression - /^he/ checks if the specified line starts with the substring he.

Conclusion

In this tutorial, we've taken a look at how to check if a string starts with a substring in vanilla JavaScript, using the startsWith() method, as well as Regular Expressions.