gpt4 book ai didi

javascript - 如何拆分camelCase字符串并检查每个拆分单词是否为数组的一部分?

转载 作者:行者123 更新时间:2023-12-03 07:18:32 26 4
gpt4 key购买 nike

假设我有一个单词数组和一些 camel案例字符串,如下所示:

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"));


我究竟做错了什么?

最佳答案

对于这种特殊情况,我将使用lookahead assertion (?=...),它是一种非捕获结构,将直接与String::split()方法一起使用。当字符串以大写字母开头时,这将解决数组上额外生成的empty string元素的问题。我也将尝试Array::includes()来交换indexOf()

var arr = ["hello", "have", "a", "good", "day", "stackoverflow"];

function checkString(wordArray, str)
{
return str.split(/(?=[A-Z])/g).every(
e => wordArray.includes(e.toLowerCase())
);
}

console.log("should return true ->" + checkString(arr, "HelloStackoverflow"));
console.log("should return false ->" + checkString(arr, "itIsAwfullyColdDayToday"));

关于javascript - 如何拆分camelCase字符串并检查每个拆分单词是否为数组的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com