Check if String starts with one of Multiple Values in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Hannah Skelly

Check if String starts with one of Multiple Values #

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.

index.js
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.

The 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.

The startsWith method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.
index.js
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.

This approach is definitely not as elegant and direct as using the startsWith method, but it gets the job done if you have to support Internet Explorer.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee