+ 1
how to count individual repeated word in a text, not repeated character in a text...
-I try using: function countWord(string, word) { return string.split(word).length - 1; } var text="We went down to the stall, then down to the river today."; var count=countWord(text,"to"); console.log(count);//3 -result is 3 instead of 2(how to fix this in es6);
4 Respostas
+ 5
use regexp to detect word boundaries:
split(new RegExp("\\b"+word+"\\b"))
or, split string into words by splitting at spaces and count matching words ^^
return string.split(" ").filter(w => w==word).length;
you could improve last code by using regexp too, and split at consecutive spaces and/or not letters char...
split(/\s+/)
split(/[^a-z]+/i)
+ 4
var countWord = (string, word) => string.split(" ").filter(w=>w===word).length;
https://code.sololearn.com/cR4hHIli4rq0/?ref=app
+ 3
Your function has split the text into four parts because the word today also has a to. ☺️
You need to first select words from the text, and only then count the desired word.
+ 1
" to " not "to"
also check if text begins with "to " or ends with " to"