2017-06-12 297 views
-2

我想從推文列表中過濾掉單詞,如果數組中出現兩個以上的單詞,則退出循環。字符串數組匹配字符串

說我有一個字符串I was following someone the other day that looked a bit grumpy

我有一個字符串數組:

[ 
    "followback", 
    "followers", 
    "grumpy cat", 
    "gamergate", 
    "quotes", 
    "facts", 
    "harry potter" 
] 

有沒有一種方法,我可以匹配它不會通過.indexOf這將只匹配拾起短語grumpy catgrumpy

const yourstring = 'I was following someone the other day that looked a bit grumpy' 
 

 
const substrings = [ 
 
    "followback", 
 
    "followers", 
 
    "grumpy cat", 
 
    "gamergate", 
 
    "quotes", 
 
    "facts", 
 
    "harry potter" 
 
] 
 

 
let len = substrings.length; 
 

 
while(len--) { 
 
    if (yourstring.indexOf(substrings[len])!==-1) { 
 
    console.log('matches: ', substrings[len]) 
 
    } 
 
}

+0

你想馬赫'grumpy'或'cat'? – baao

+1

那麼,在一個字符串中使用「脾氣暴躁的貓」是什麼呢?爲什麼不把它作爲兩個單獨的單詞存儲在你的數組中? – trincot

+0

你有什麼要告訴我們_兩個以上的word_先決條件? – baao

回答

2

你可以只用於循環做了。

for (var x = 0; x<substrings.length; x++) { 
    if (substrings[x] == 'your string') { 
     // do what you want here 
    } 
} 

如果您正在尋找一個確切的字符串,那麼只要做到這一點,應該工作。如果您嘗試將部分字符串與數組中的字符串進行匹配,則IndexOf將起作用。但我會堅持使用for循環和精確匹配

0

可以使用split(' ')將子字符串拆分爲單詞數組,然後使用includes方法檢查是否包含yourstring中的任何單詞。

const yourstring = 'I was following someone the other day that looked a bit grumpy'; 
 

 
const substrings = [ 
 
    "followback", 
 
    "followers", 
 
    "grumpy cat", 
 
    "gamergate", 
 
    "quotes", 
 
    "facts", 
 
    "harry potter" 
 
]; 
 

 
console.log(substrings.filter(x => x.split(' ').some(y => yourstring.includes(y))));

這裏是如何使用的Ramda庫做相同的:

const yourstring = 'I was following someone the other day that looked a bit grumpy'; 
 

 
const substrings = [ 
 
    "followback", 
 
    "followers", 
 
    "grumpy cat", 
 
    "gamergate", 
 
    "quotes", 
 
    "facts", 
 
    "harry potter" 
 
]; 
 

 
const anyContains = x => R.any(R.flip(R.contains)(x)); 
 

 
console.log(R.filter(R.compose(anyContains(yourstring), R.split(' ')), substrings));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>