Match two strings with the same word in JavaScript

2019-06-10 15:11发布

问题:

Given two strings, how can I do something if both strings have one word in common?

For example: "foo bar" and "foo line" both have the word "foo". The strings could be 3 words long or more, like "foo bar" and "blue foo line".

What I've tried so far:

var m = "foo bar";
var n = "foo line";
if(m.match(/n/g)){
  alert("match");
}

回答1:

http://jsbin.com/iwalam/3/edit

better version :

var m = "foo bar".split(' ');

var n = "foo line".split(' ');
var isOk=0;

    for (var i=0;i<m.length;i++)
    {
    for (var j=0;j<n.length;j++)

    {
      var reg = new RegExp("^"+m[i]+"$", "gi");

    if (n[j].match(reg) )
    {isOk=1;break;}
    }
    }

if (isOk==1)
  alert("match");


回答2:

Here's a more explicit version, without the unneeded regular expression:

function hasWordMatch(a, b, case_sensitive) {
    if (case_sensitive !== true) {
        a = a.toLowerCase();
        b = b.toLowerCase();
    }
    var a_parts = a.split(' ');
    var b_parts = b.split(' ');
    var a_length = a_parts.length;
    var b_length = b_parts.length;
    var i_a, i_b;

    for (i_a = 0; i_a < a_length; i_a += 1) {
        for (i_b = 0; i_b < b_length; i_b += 1) {
            if (a_parts[i_a] === b_parts[i_b]) {
                return true;
            }
        }
    }
    return false;
}

console.log(hasWordMatch("foo bar", "foo baz")); // true
console.log(hasWordMatch("foo bar", "bada bing")); // false
console.log(hasWordMatch("FOO BAR", "foo baz")); // true
console.log(hasWordMatch("FOO BAR", "foo baz", true)); // false

The regex in your question is case sensitive, but this version is case insensitive by default. You can make is case sensitive by passing true as the third argument.

It's also up on JSFiddle: http://jsfiddle.net/WQBSv/