【发布时间】:2019-06-21 21:05:44
【问题描述】:
假设我有一个 单词数组 和几个 camelCase 字符串,如下所示:
var arr = ["hello", "have", "a", "good", "day", "stackoverflow"];
var str1 = "whenTheDayAndNightCollides";
var str2 = "HaveAGoodDay";
var str3 = "itIsAwfullyColdDayToday";
var str4 = "HelloStackoverflow";
如何将camelCase 单词拆分为单独的字符串,将每个拆分字符串(转换为小写)与arr 数组元素进行比较,如果每个拆分字符串都是指定数组的一部分,则返回true?
"whenTheDayAndNightCollides" // should return false since only the word "day" is in the array
"HaveAGoodDay" // should return true since all the words "Have", "A", "Good", "Day" are in the array
"itIsAwfullyColdDayToday" // should return false since only the word "day" is in the array
"HelloStackoverflow" // should return true since both words "Hello" and "Stackoverflow" are in the array
正如其他SO thread 中所建议的那样,我尝试使用every() 方法和indexOf() 方法来测试是否可以在数组中找到每个拆分字符串,如以下代码所示片段,但它不起作用:
var arr = ["hello", "have", "a", "good", "day", "stackoverflow"];
function checkString(wordArray, str)
{
// split the camelCase words
var x = str.replace(/([A-Z])/g, ' $1').split(" ");
return x.every(e => {
return wordArray.indexOf(e.toLowerCase()) >= 0;
});
}
console.log("should return true ->" + checkString(arr, "HelloStackoverflow"));
console.log("should return false ->" + checkString(arr, "itIsAwfullyColdDayToday"));
我做错了什么?
【问题讨论】:
标签: javascript regex