我需要在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');
}
}
答案 0 :(得分:4)
您的代码中存在一个小问题。你必须搬家
var count = 0;
在for循环之外。
答案 1 :(得分:2)
移动
var count = 0;
在你的循环之外
答案 2 :(得分:2)
您的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');
}
}
答案 3 :(得分:0)
您可以使用正则表达式来计算出现次数
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');
}
答案 4 :(得分:0)
已经回答,但这是获得计数的简短版本:
function getWordCount(word, text) {
if(arguments.length === 0) return;
var count = 0;
text.split(" ").forEach(function(val) {
if(val === word) count++;
});
}
答案 5 :(得分:0)
这一行解决方案似乎有效。请注意,它会在句子的头部和尾部附加一个空格,以便在末尾捕获匹配的单词。这也可以使用纯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');