Compare words in strings
我正在尝试比较字符串中的单词。这就是我想要做的:
1 2 3 4 5 6 7 | var string1 ="Action, Adventure, Comedy"; var string2 ="Action Horror"; if (string1 have a word from string 2 == true) { alert("found!"); } |
我试过match(),但在我的情况下,它试图找到"动作恐怖"而不是"动作"和"恐怖"两个词。
你可以用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); |
或
1 2 3 4 5 6 7 8 9 10 11 12 | 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-如何检查字符串是否包含特定单词
具有
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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/splithttps://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/indexof
声明两组:
1 | var Set set1,ser2; |
。
将string1复制到set1,将string2复制到set2
(不知道怎么做)。然后有:
var交集=新集合([x表示(集合1的x)如果(集合2.has(x))]));
1 | if intersection.prototype.size>0 |
两个字符串(和集合)都有共同的词。