DEV Community

ivkeMilioner
ivkeMilioner

Posted on • Updated on

I have a problem, counting words didn't start from 1?

This is my code

var words = input.value.match(/\s[\w\u0402-\u045f]+/ig);

if (words) {
    wordCount.innerHTML = words.length;
} else {
    wordCount.innerHTML = 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
fcrozetta profile image
Fernando Crozetta

I think your regex is excluding the first word.
I chenged the example in developer.mozilla.org/en-US/docs/W...

var paragraph = 'The quick';
var regex = /\s[\w\u0402-\u045f]+/ig;
var found = paragraph.match(regex);

console.log(found);
console.log(found.length)

Can you share what are you trying to do with this code?

Collapse
 
ivkemilioner profile image
ivkeMilioner
Collapse
 
ivkemilioner profile image
ivkeMilioner • Edited

I need accurate counting. Code didn't count first word.

Collapse
 
fcrozetta profile image
Fernando Crozetta

I think the regex expression is not correct, for some reason. Alternatively, you can try to split the string into an array, and loop each element. Not sure about performance in this case

Thread Thread
 
ivkemilioner profile image
ivkeMilioner

It is correct. Counting Cyrillic words. But it starts counting from 0 not from 1.

Thread Thread
 
fcrozetta profile image
Fernando Crozetta

check the code i posted above. It has 2 words, but if you print found, it shows only the second word. The length is 1.
So, it starts counting on 1, but for some reason, your regex is skipping the first word. If you have only one word in the paragraph variable, the result is null.

Thread Thread
 
ripaz profile image
Ripaz

You are checking if space exists before word. Since first word doesn't have space before it, it fails to count it.

Collapse
 
ripaz profile image
Ripaz • Edited

Try this, it includes beginning of the text or white space check.

/[^|\s][\w\u0402-\u045f]+/ig