2016-02-27 96 views
1

我想比較單詞中的單詞。這就是我想要做的:比較字符串中的單詞

var string1 = "Action, Adventure, Comedy"; 
var string2 = "Action Horror"; 

if (string1 have a word from string 2 == true) 
{ 
    alert("found!"); 
} 

我試圖匹配(),但在我的情況,它試圖找到「恐怖行動」而不是「行動」和「恐怖」的字眼。

+0

http://stackoverflow.com/a/21081760/4689622 –

+0

可能重複[JavaScript/jQuery - 如何檢查一個字符串是否包含特定的單詞](http://stackoverflow.com/questions/5388429/javascript- jQuery的如何做 - 檢查 - 如果-A-字符串包含特定的詞) – mcy

回答

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

0

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

-1

聲明兩組:

var Set set1,ser2; 

將string1複製到set1中並將string2複製到set2中

(不知道如何做到這一點)。然後得到:

var intersection = new Set([x for(set1的x))if(set2.has(x))]);

if intersection.prototype.size>0 

有兩個字符串(和集合)共有的詞。