Check if a string starts with any of the strings in an array

Viewed 3289

In javascript, how can I check if a string starts with any of the strings in an array.

For example,

I have an array of strings,

const substrs = ['the', 'an', 'I'];

I have a string

const str = 'the car';

How can I check if str starts with any of the strings in substrs?

4 Answers

You can use a combination of Array.prototype.some and String.prototype.startsWith, both of which are ES6 features:

const substrs = ['the', 'an', 'I'];
function checkIfStringStartsWith(str, substrs) {
  return substrs.some(substr => str.startsWith(substr));
}

console.log(checkIfStringStartsWith('the car', substrs)); // true
console.log(checkIfStringStartsWith('a car', substrs)); // false
console.log(checkIfStringStartsWith('i am a car', substrs));  // false
console.log(checkIfStringStartsWith('I am a car', substrs));  // true

If you want the comparsion to be done in a case-insensitive manner, then you will need to convert the string to lowercase as well:

const substrs = ['the', 'an', 'I'];
function checkIfStringStartsWith(str, substrs) {
  return substrs.some(substr => str.toLowerCase().startsWith(substr.toLowerCase()));
}

console.log(checkIfStringStartsWith('the car', substrs)); // true
console.log(checkIfStringStartsWith('a car', substrs)); // false
console.log(checkIfStringStartsWith('i am a car', substrs));  // true (case-insensitive)
console.log(checkIfStringStartsWith('I am a car', substrs));  // true

One approach would be to build a regex alternation of the keywords in the substrs array. Then, use test() on the input to check for a match:

const substrs = ['the', 'an', 'I'];
const str = 'the car';
regexp = new RegExp('^(?:' + substrs.join('|') + ')\\b');
console.log(regexp);
if (regexp.test(str)) {
    console.log("MATCH");
}

Here I have also printed out the regular expression being used so that it is clear.

const check = (arr, str) => {
    const firstWord = str.substr(0, str.indexOf(" "));
    return arr.includes(firstWord);
}

const substrs = ['thee', 'an', 'I', 'The', 'the'];
const str = 'the car';

console.log(check(substrs, str)); //true

const substrs = ['the', 'an', 'I'];
const str = 'the car';

let result = substrs.filter(s => str.startsWith(s));

console.log(result);

Related