2016-12-06 27 views
1

我有兩個字符串:檢查子存在於另一個字符串,正則表達式

var first = "913 DE 6D 3T 222" 
var second = "913 DE 3T 222" 

我要檢查,如果second存在於first,最好用regex。問題是,indexOfincludes返回該second出現在first,這是錯誤的(僅6D的區別):

first.indexOf(second) 
-1 

first.includes(second) 
false 
+0

你是什麼的定義 「包含」 在這裏? –

+0

http://stackoverflow.com/questions/1789945/how-to-check-if-one-string-contains-another-substring-in-javascript – AshBringer

+0

也許你應該拆分你的第二個字符串,並檢查值是否包含在字符串1?第二**不是完全出現在第一,這就是爲什麼這些方法正常工作 – XtremeBaumer

回答

3

使用String#splitArray#every方法。

var first = "913 DE 6D 3T 222"; 
 
var second = "913 DE 3T 222"; 
 

 
console.log(
 
    second 
 
    // split the string by space 
 
    .split(' ') 
 
    // check all strings are contains in the first 
 
    .every(function(v) { 
 
    return first.indexOf(v) > -1; 
 

 
    // if you want exact word match then use regex with word 
 
    // boundary although you need to escape any symbols which 
 
    // have special meaning in regex but in your case I think all are 
 
    // alphanumeric char so which is not necessary 
 

 
    // return (new RegExp('\\b' + v + '\\b')).test(first); 
 
    }) 
 
)


FYI:對於較舊的瀏覽器檢查polyfill option of every method


+0

@ user1665355:在註釋 –

1

這是一個更優雅的解決方案。

首先,我正在使用map函數。在我們的例子中,它返回一個像這樣的數組:

[true,true,true,true]。然後,使用reduce函數和logical operators我們將獲得一個單一值。如果array包含至少一個false值,則最終結果將爲false

var first = "913 DE 6D 3TT 222"; 
 
var second = "913 DE 3T 222"; 
 
console.log(second.split(' ').map(function(item){ 
 
    return first.includes(item); 
 
}).reduce(function(curr,prev){ 
 
    return curr && prev; 
 
}));

+0

添加@亞歷-Iounut正則表達式選項檢查Mihai這將檢查所有字符和數字是否在第一個從第二個出現? – user1665355

+0

@ user1665355,是的,我使用的邏輯運算符 –

+0

如果第一字符串是'VAR返回假第一= 「913 DE 6D 3TT 222」 .split(」「);',請注意在'3TT'一個更'T'。應該仍然是真實的,因爲第二個中的所有角色仍然存在於第一個中。 – user1665355

0

使用String.match()功能和特定的正則表達式模式的解決方案:

我已經改變first串做出更復雜的情況下,重複添加DE價值。

var first = "913 DE 6D 3T 222 DE", 
 
    second = "913 DE 3T 222", 
 
    count = second.split(' ').length; 
 

 
var contained = (count == first.match(new RegExp('(' + second.replace(/\s/g, "|") + ')(?!.*\\1)', "gi")).length); 
 
console.log(contained);

(?!.*\1) - 爲負預測先行斷言,以避免重複匹配

+0

tnx!也是一個好的解決方案 – user1665355

相關問題