DEV Community

Discussion on: Let's talk about how powerful split function is

Collapse
 
damnjan_37 profile image
Damnjan Lukovic

Good idea! However, there is an issue with this approach. If you input a string with special characters, like this: "Hello - world", it would count it as 3 words instead of 2. Your code registers anything between two whitespace characters as a word. To solve that problem, we can use regex.

\w is used for matching word characters - it matches a letter, a number or an underscore. To match the whole word, we simply write \w+

So instead of

const wordsArr = line.trim().split(/\s/); 
words += wordsArr.length;

We could write

const wordsArr = line.match(/\w+/g) || []
words += wordsArr.length;

If we want to match alphabetical characters only, we can use [a-zA-Z] instead of \w, or we can play around with the regex based on our needs.

Bonus: you can use map and reduce to make this code shorter:

function countWords(linesArr) {
  return linesArr
    .map(line =>  (line.match(/\w+/g) || []).length)
    .reduce((curr, next) => curr + next)
}

Hope this helps!

Collapse
 
jalal246 profile image
Jalal 🚀

It helps Damnjan, thanks! I still need to count characters and spaces tho maybe using match(/\s/g) will do with total length.