+ 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);

14th Jul 2021, 8:26 AM
🤖Web Gig🤖
🤖Web Gig🤖 - avatar
4 odpowiedzi
+ 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)
14th Jul 2021, 8:42 AM
visph
visph - avatar
+ 4
var countWord = (string, word) => string.split(" ").filter(w=>w===word).length; https://code.sololearn.com/cR4hHIli4rq0/?ref=app
14th Jul 2021, 1:49 PM
Calviղ
Calviղ - avatar
+ 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.
14th Jul 2021, 8:42 AM
Solo
Solo - avatar
+ 1
" to " not "to" also check if text begins with "to " or ends with " to"
14th Jul 2021, 10:02 AM
Oma Falk
Oma Falk - avatar