Reputation: 13
I need to write a function in javascript, which finds a string in a text and prints how many times the string is found in the text. Here is my code, It's not working for some reason.... Please help
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');
}
}
Upvotes: 1
Views: 73
Reputation: 7229
This one line solution appears to work. Note that it appends a space to the head and tail of the sentence to catch matching words at ends. This could be done with a pure RegExp too, but then it wouldn't be one line ... and I like simple solutions.
return (' ' + text.toLowerCase() + ' ').split( ' ' + word.toLowerCase() + ' ' ).length - 1;
And refactoring the original code we can eliminate 10 extraneous lines and a loop:
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');
Upvotes: 0
Reputation: 1650
Already answered but this is a short version of getting the count:
function getWordCount(word, text) {
if(arguments.length === 0) return;
var count = 0;
text.split(" ").forEach(function(val) {
if(val === word) count++;
});
}
Upvotes: 0
Reputation: 3518
You could just use a regular expression to count the occurences
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');
}
Upvotes: 0
Reputation: 8488
Your count
variable should be outside of your for loop
, else you are resetting it everytime you enter the 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');
}
}
Upvotes: 2
Reputation: 28475
There is a small problem in your code. You have to move
var count = 0;
outside the for loop.
Upvotes: 4