This is easily achieved either through the
startsWith() method, or regular expressions.
Check if String Starts with Another String with startsWith()
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
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.
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
^ meta character 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
startsWith() method, as well as Regular Expressions.