Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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.

Home Screencasts Best of Newsletter Search X