Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Hannah Skelly
To check if a string starts with one of multiple values, use the logical OR
(||) operator to chain multiple calls to the startsWith()
method. If either
condition is satisfied, true
will be returned, otherwise false
will be
returned.
const str = 'one two three'; if (str.startsWith('one') || str.startsWith('two')) { console.log('✅ string starts with either value'); } else { console.log('⛔️ string does NOT start with either value'); }
We used the String.startsWith method to check if a string starts with a specific substring.
startsWith
method returns true
if the string starts with the substring and false
otherwise.The logical OR (||) operator allows us to chain multiple conditions.
The logical OR (||) operator returns the value to the left if it's truthy, otherwise it returns the value to the right.
If either call to the startsWith
method returns true
, our if
block will
run.
startsWith
method is not supported in Internet Explorer. If you have to support the browser, use the indexOf
method instead.const str = 'one two three'; if (str.indexOf('one') === 0 || str.indexOf('two') === 0) { console.log('✅ string starts with either value'); } else { console.log('⛔️ string does NOT start with either value'); }
The String.indexOf method returns the index of the first occurrence of a substring in a string.
If the substring is not contained in the string, the method returns -1
.
If the substring is found in the string at index 0
, we can conclude that the
string starts with the substring.
If either call to the indexOf
method returns 0
, our if
block will run.
startsWith
method, but it gets the job done if you have to support Internet Explorer.