gpt4 book ai didi

javascript - 比较字符串中的单词

转载 作者:行者123 更新时间:2023-12-01 05:33:15 24 4
gpt4 key购买 nike

我正在尝试比较字符串中的单词。这就是我想做的:

var string1 = "Action, Adventure, Comedy";
var string2 = "Action Horror";

if (string1 have a word from string 2 == true)
{
alert("found!");
}

我尝试过 match(),但在我的情况下,它尝试查找“Action Horror”而不是“Action”和“Horror”词。

最佳答案

您可以使用 match() 执行类似的操作 reduce()

var string1 = "Action, Adventure, Comedy";
var string2 = "action Horror";

var strArr = string1.match(/\b\w+?\b/g)
//getting all words from string one
.map(function(v) {
return v.toLowerCase();
});
//converting strings to lower case for ignoring case

var res = string2.match(/\b\w+?\b/g)
// getting words from second string
.reduce(function(a, b) {
return a || strArr.indexOf(b.toLowerCase()) != -1;
//checking string in first word array
}, false);
// also set initial value as false since no strings are matched now

console.log(res);

或者

var string1 = "Action, Adventure, Comedy";
var string2 = "action Horror";

var res = string2.match(/\b\w+?\b/g)
// getting words from second string
.reduce(function(a, b) {
return a || new RegExp('\\b' + b + '\\b', 'i').test(string1);
//checking string in first string
}, false);
// also set initial value as false since no strings are matched now

console.log(res);

引用:JavaScript/jQuery - How to check if a string contain specific words

关于javascript - 比较字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667843/

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