字符串数组与字符串匹配

时间:2017-06-12 19:13:58

标签: javascript arrays string

我正在尝试从推文列表中过滤掉单词,如果数组中出现两个以上的单词,则退出循环。

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

我有一个字符串数组:

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

有没有一种方法可以匹配grumpy cat短语,.indexOf只能与grumpy匹配?

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])
  }
}

2 个答案:

答案 0 :(得分:2)

你可以做一个for循环。

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

如果您正在寻找一个确切的字符串,那么就在上面做,这应该有用。如果您尝试将部分字符串与数组中的字符串匹配,IndexOf将起作用。但我会坚持使用for循环和完全匹配

答案 1 :(得分:0)

您可以使用split(' ')将子字符串拆分为单词数组,然后使用yourstring方法检查includes中是否包含任何字词。

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>