Javascript 在字符串中查找短语

Javascript 在字符串中查找短语,javascript,search,Javascript,Search,我想在字符串中找到一个单词数组。我是用JavaScript做的 var lotsOfText=“blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computers”; var textToFind=[“胡说八道”、“随机填充”、“堆叠流计算”]; var计数器=0; 对于(变量i=0;is+=i?1:0)indexOf将为您提供字符串中任意字母组合的起始索引,如果单词未出现在字符串中,则为-1

我想在字符串中找到一个单词数组。我是用JavaScript做的

var lotsOfText=“blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computers”;
var textToFind=[“胡说八道”、“随机填充”、“堆叠流计算”];
var计数器=0;
对于(变量i=0;i
var lotsOfText=“blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computers”;
var textToFind=[“胡说八道”、“随机填充”、“堆叠流计算”];
var计数器=0;
textToFind.forEach(函数(frase){
计数器+=(lotsOfText.match(新的RegExp(frase,'g'))| |[])长度;
});

控制台日志(计数器)
您可以使用
.search()
。我创建了一个jsbin来帮助您:

基本上,它看起来是这样的:

var lotsOfText = "blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computersc ience";
var textToFind = ["blah", "random stuff", "stackover flow comput"];
var counter = 0;

textToFind.forEach(x => {
  if (lotsOfText.search(x) > -1) {
    counter++;
  }
});
现在,这并没有寻找确切的措辞,但我不确定你在追求什么。例如,它查找“blah”是因为“blahmehoobar”。

只需使用

返回
sometext中第一个出现的
str
的位置(第一个字符是
0
),该位置从
start

如果未找到
str
,则
indexOf
返回
-1

对于数组中的每个字符串,将在
lotsOfText
中搜索一个匹配项。如果找到一个匹配项,
计数器
将递增,并在上次找到的匹配项之后搜索同一字符串的另一个匹配项


如果没有(更多)出现,则退出
while
循环,并处理数组中的下一个字符串。

您可以使用正则表达式检查每个字符串是否存在(以及出现的次数):

var lotsOfText = "blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computersc ience";
var textToFind = ["blah", "random stuff", "stackover flow comput"];
var counter = 0;

textToFind.map(function(word) {
  // create the regular expression ('g' means will find all matches)
  var re = new RegExp(word, 'g');
  // add the number of matches found in lotsOfText
  counter += (lotsOfText.match(re) || []).length || 0;
});

console.log(counter)

这段代码只计算匹配的总数(即使它们作为子字符串出现),但您可以看到基本结构,并且可以轻松地对其进行操作以满足您的确切需要。

那么计数器应该是什么,3?
textToFind.map(word=>lotsOfText.includes(word)).reduce((s,i)=>s+=i?1:0)
indexOf将为您提供字符串中任意字母组合的起始索引,如果单词未出现在字符串中,则为-1。
var counter=textToFind.reduce((a,b)=>a+(lotsOfText.includes(b)?1:0),0)
可能应该提到IE或早期版本的Edge以及其他半常用浏览器不支持“includes()”。您可能需要一个polyfill或使用indexOf(),如某些答案所示。如果字符串中有一个单词多次出现,该怎么办?您的解决方案不会只看一个事件而忽略其他事件吗?@HumanCyborgRelations您可能应该在问题中更好地说明您需要实现的目标。@HumanCyborgRelations更新,很抱歉,我在你的问题中读不到更多occurrences@HumanCyborgRelations如果我的答案是正确的,你应该把它标为正确
sometext.indexOf( str, start )
var lotsOfText = "blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computersc ience";
var textToFind = ["blah", "random stuff", "stackover flow comput"];
var counter = 0;

textToFind.map(function(word) {
  // create the regular expression ('g' means will find all matches)
  var re = new RegExp(word, 'g');
  // add the number of matches found in lotsOfText
  counter += (lotsOfText.match(re) || []).length || 0;
});

console.log(counter)