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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With