Subscribe

JavaScript startsWith and multiple conditions

✍️

How to use startsWith to check for multiple starting strings in JavaScript

1 Dec, 2021 · 2 min read

You might have heard of the JavaScript startsWith method. It can check if a particular string starts with another string.

To give you a demonstration it would work something like this:

const string = 'Hi, and welcome from JavaScript';
console.log(string.startsWith('Hi'));
// true
console.log(string.startsWith('Hello'));
// false

Checking for multiple conditions with startsWith

But what if we want to check if a string starts with a multiplication of strings?

So let’s say Hi and Hello would be fine.

We could use a conditional statement. However, this might get very unorganized if we decide to allow more strings at a later stage.

However, it would look like this:

const string = 'Hi, and welcome from JavaScript';
const result = string.startsWith('Hi') || string.startsWith('Hello');
console.log(result);
// true

Another way is to use the same method on a predefined array. I quite like the simplicity and naming of this method as it states what’s happening.

This is what it looks like:

const result = ['Hi', 'Hello'].some((word) => string.startsWith(word));
console.log(result);
// true

Feel free to try these out in the following CodePen.

See the Pen JavaScript startsWith and multiple conditions by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter