比较字符串中的单词



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

var string1 = "Action, Adventure, Comedy";
var string2 = "Action Horror";
if (string1 have a word from string 2 == true)
{
    alert("found!");
}

我尝试过match(),但在我的情况下,它试图找到"动作恐怖"而不是"动作"和"恐怖"词。

您可以使用

match()reduce()

var string1 = "Action, Adventure, Comedy";
var string2 = "action Horror";
var strArr = string1.match(/bw+?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(/bw+?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(/bw+?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 - 如何检查字符串是否包含特定单词

具有 String.splitString.indexOfArray.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/splithttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

声明两个集合:

    var Set set1,ser2;
将字符串

1 复制到集合 1 中,将字符串 2 复制到集合 2

(不知道该怎么做)。 然后有:

var 交集 = new Set([x for (x of set1) if (set2.has(x))]);

    if intersection.prototype.size>0

字符串(和集合)都有共同的单词。

相关内容

  • 没有找到相关文章

最新更新