Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 469
Akhil Chandran Avatar asked Dec 22 '25 00:12

Akhil Chandran


1 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
like image 105
Terry Avatar answered Dec 24 '25 13:12

Terry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!