[英]Search ot string in a array Javascript
我需要用javascript写一个函数,该函数在文本中找到一个字符串,并打印在文本中找到该字符串的次数。 这是我的代码,由于某种原因无法正常工作。
var word = 'text',
text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.';
searchWord(word, text);
function searchWord(word, text) {
switch (arguments.length) {
case 1: console.log('Invalid input, please try again'); break;
case 2: var array = text.split(' ');
for (var i = 0; i < array.length; i++) {
var count = 0;
if (array[i] === word) {
count ++;
}
}
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
}
您的代码中有一个小问题。 你必须搬家
var count = 0;
在for循环之外。
移动
var count = 0;
在你的循环之外
您的count
变量应位于for loop
,否则每次进入循环时都将其重置。
function searchWord(word, text) {
switch (arguments.length) {
case 1: console.log('Invalid input, please try again'); break;
case 2: var array = text.split(' ');
var count = 0;//Place it here.
for (var i = 0; i < array.length; i++) {
if (array[i] === word) {
count ++;
}
}
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
}
您可以只使用正则表达式来计算发生次数
var word = 'text', text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.'; searchWord(word, text); function searchWord(word, text) { var re = new RegExp(""+text+"", "g"); var count = (text.match(/text/g) || []).length; console.log('Word ' + word + ' is repeated in the text ' + count + ' times'); }
已经回答,但这是获得计数的简短版本:
function getWordCount(word, text) {
if(arguments.length === 0) return;
var count = 0;
text.split(" ").forEach(function(val) {
if(val === word) count++;
});
}
这一行解决方案似乎可以工作。 请注意,它会在句子的开头和结尾处添加一个空格,以在结尾处捕获匹配的单词。 这也可以用一个纯RegExp来完成,但是那不是一行...而且我喜欢简单的解决方案。
return (' ' + text.toLowerCase() + ' ').split( ' ' + word.toLowerCase() + ' ' ).length - 1;
重构原始代码,我们可以消除10条多余的代码和一个循环:
function searchWord(word, text) { return (' ' + text.toLowerCase() + ' ').split( ' ' + word.toLowerCase() + ' ' ).length - 1; } var word = 'text', text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.'; console.log('Word ' + word + ' is repeated in the text ' + searchWord(word,text) + ' times');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.