【问题标题】:Compare words in strings比较字符串中的单词
【发布时间】:2016-06-10 14:53:27
【问题描述】:

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

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”字样。

【问题讨论】:

标签: javascript jquery compare match


【解决方案1】:

您可以使用 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

【讨论】:

    【解决方案2】:

    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/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

    【讨论】:

      【解决方案3】:

      声明两个集合:

          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
      

      两个字符串(和集合)都有一些共同的词。

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多