我想在String中找到一系列单词。我是用JavaScript做的,
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;
for (var i = 0; i < textToFind.length; i++) {
var text = textToFind[i];
for (var j = 0; j < lotsOfText.length; j++) {
if (text.charAt(0) === lotsOfText.charAt(j)) {
if (text === lotsOfText.substring(j, text.length)) {
counter++;
j = text.length - 1;
}
}
}
}
console.log(counter);
&#13;
现在,计数器= 1
我不知道哪里出错了。
此外,还有更好/更快的方法吗?也许某些东西不需要两个for循环和多次遍历字符串文本?
编辑:我想查找字符串中每个单词的所有出现次数。所以,就像现在一样,计数器应该返回5
答案 0 :(得分:3)
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(function(frase){
counter+=(lotsOfText.match(new RegExp(frase, 'g')) || []).length;
});
console.log(counter);
&#13;
答案 1 :(得分:0)
您可以使用.search()
。我已经创建了 jsbin 来帮助您:http://jsbin.com/seregexuxi/edit?js,console
基本上,它看起来像这样:
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++;
}
});
现在,这并没有找到确切的措辞,但我不确定你之后会怎样。例如,它找到&#34; blah&#34;因为&#34; blahmehfoobar&#34;。
答案 2 :(得分:0)
只需使用indexOf()
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;
var j;
for (var i = 0; i < textToFind.length; i++) {
j = 0;
while( true ) {
j = lotsOfText.indexOf( textToFind[ i ], j );
if( j !== -1 ){
counter++;
j += textToFind[ i ].length;
} else {
break;
}
}
}
基本上
sometext.indexOf( str, start )
从位置0
开始,str
内首次出现sometext
的位置(第一个字符为start
)
如果找不到str
,则indexOf
会返回-1
对于数组中的每个字符串,在lotsOfText
中搜索一个事件。如果找到某个匹配项,counter
会增加,并且在找到最后一个匹配项后搜索另一个相同字符串的匹配项。
当没有找到(更多)出现时,退出while
循环并处理数组中的下一个字符串。
答案 3 :(得分:0)
您可以使用正则表达式检查每个字符串的存在(和出现次数):
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)
此代码只计算匹配的总数(即使它们作为子字符串出现),但您可以看到基本结构,并且可以轻松地操作它以满足您的确切需求。