我正在尝试比较字符串中的单词。这就是我想要做的事情:
var string1 = "Action, Adventure, Comedy";
var string2 = "Action Horror";
if (string1 have a word from string 2 == true)
{
alert("found!");
}
我尝试过match(),但在我的情况下,它试图找到" Action Horror"而不是"行动"和#34;恐怖"词语的
答案 0 :(得分:1)
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
答案 1 :(得分:0)
使用String.split
,String.indexOf
和Array.foreach
函数的解决方案:
var string1 = "Action, Adventure, Comedy, Horror";
var string2 = "Action Horror";
var str1_arr = string1.split(', ');
str1_arr.forEach(function (v) {
if (string2.indexOf(v) !== -1) {
console.log("string '"+ v +"'(from string1) was found in string2 in position " + string2.indexOf(v));
}
});
// the output:
string 'Action'(from string1) was found in string2 in position 0
string 'Horror'(from string1) was found in string2 in position 7
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
答案 2 :(得分:-1)
宣布两套:
var Set set1,ser2;
将string1复制到set1,将string2复制到set2
(不知道该怎么做)。然后有:
var intersection = new Set([x for(x of set1)if(set2.has(x))]);
if intersection.prototype.size>0
两个字符串(和集合)都有共同的词。