šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

JavaScript multiple conditions for string startsWith

Recently I've had a situation where we needed to test if a given JS string starts with any of the values from within an array.

So, basically need to check if a string starts with any of the possible multiple values.

It should work something like this:

const words = ["river", "watch", "house"]

const test1 = "house lannister" // true
const test2 = "game of thrones" // false

We have the Javascript startsWith() function that tests if a string begins with another string. Would have been great to have a startsWith([]) option but it seems we cannot send multiple values to be tested as a starting string.

So, we will need to write our own function:

const startsWithAny = (s, words) => words.some( w => s.startsWith(w))

const test1 = "house lannister"
const test2 = "game of thrones"
const words = ["river", "watch", "house"]

startsWithAny(test1, words) // true
startsWithAny(test2, words) // false

The some() function will loop through an array and returns true (and stops) if the test is true for one element in that array.

Keep in mind that this function will is case-sensitive. So, if you have:

const test = "House Lannister"
const words = ["river", "house"]

Then startsWithAny(test, words) will return false.

We can add the case sensitive option for our function. The caseSensitive will have a default parameter value of true:

const startsWithAny = (s, words, caseSensitive = true) => {
  if (!caseSensitive) {
    s = s.toLowerCase()
    words = words.map(v => v.toLowerCase())
  }
  return words.some( w => s.startsWith(w))
}

const test1 = "house lannister"
const test2 = "House Lannister"

const words = ["river", "watch", "house"]

startsWithAny(test1, words) // true
startsWithAny(test2, words, false) // true

You can play here with the full codepen.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *