[英]Check if a string starts with any of the strings in an array
在 javascript 中,如何檢查字符串是否以數組中的任何字符串開頭。
例如,
我有一個字符串數組,
const substrs = ['the', 'an', 'I'];
我有一個字符串
const str = 'the car';
如何檢查 str 是否以 substrs 中的任何字符串開頭?
你可以使用Array.prototype.some
和String.prototype.startsWith
的組合,它們都是 ES6 的特性:
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
如果您希望以不區分大小寫的方式進行比較,那么您還需要將字符串轉換為小寫:
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
一種方法是在substrs
數組中構建關鍵字的正則表達式交替。 然后,在輸入上使用test()
來檢查匹配:
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"); }
這里我還打印了正在使用的正則表達式,以便清楚。
const substrs = ['the', 'an', 'I']; const str = 'the car'; let result = substrs.filter(s => str.startsWith(s)); console.log(result);
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.