gpt4 book ai didi

javascript - 当字符串中存在多个空格时,字数统计不正确

转载 作者:行者123 更新时间:2023-11-28 18:53:01 24 4
gpt4 key购买 nike

这个功能运行良好。但是如果我在 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+/);

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

关于javascript - 当字符串中存在多个空格时,字数统计不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34158594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com