字符串中存在多个空格时,字数不正确

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

本文关键字:不正确 空格 存在 字符串      更新时间:2023-09-26

此函数运行良好。但是,如果我在str中添加的空格比它给出的字数多。如有任何帮助,我们将不胜感激。

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)

尝试以下操作:

mystring.split(/'s+/);

这将在一个或多个空白字符上进行拆分,因此一行中的两个(或多个)空格将被视为一个拆分。

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

//输出:4