2017-06-12 247 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>