M Sohaib Khan
M Sohaib Khan

Reputation: 148

Word count is incorrect when multiple spaces are present in the string

This function works fine. But if i add more spaces in str than it gives the wrong count of words. Any help would be appreciated.

str = "coune me in"
var obj = {};
var regex = /[\s]/gi

function count(str){
    // total spaces in a string
    var spacesCount = str.match(regex).length;
    // words count
    var wordsCount = str.split(' ').length;
    //charetcers count
    var charsCount = str.split('').join('').length;
    //average count 
    var avgCount   = str.split(' ').join('').length/wordsCount;
    // adding it to the object  
    obj.words = wordsCount;
    obj.chars = charsCount;
    obj.avgLength = avgCount;
    obj.spaces = spacesCount;
    return obj

}
count(str)

Upvotes: 0

Views: 1167

Answers (2)

G M shakil bhuiyan
G M shakil bhuiyan

Reputation: 11

let Allah = 'Allah    is our creator.'
Allah = Allah.trim();
count = 0;
for (let i = 0; i < Allah.length; i++) {
    let char = Allah[i];
    if (char == " " && Allah[i-1] != " ") {//add here
        count++;
    }
    
}
count++;
console.log(count);

//output:4

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

Try something like:

mystring.split(/\s+/);

This will split on one or more white-space characters so two spaces (or more) in a row will be treated as just one split.

Upvotes: 3

Related Questions