字符串中存在多个空格时,字数不正确
Word count is incorrect when multiple spaces are present in the string
此函数运行良好。但是,如果我在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
相关文章:
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- Amazon S3 REST API大小不正确
- Javascript Reg Exp不正确匹配
- DIV并排,位置不正确
- 仅在IE中,javascript中的时区名称不正确
- 注意:wp_enqueue_script调用不正确.在 Wordpress 调试模式下
- 你能解释一下为什么这个javascript不正确吗
- Javascript Regexp-不接受空格,但应该接受
- 从int值来看,Javascript日期不正确
- jQuery-迭代不正确?(太长,无法执行)
- 字符串解析不正确
- 日历显示不正确
- 引导程序下拉列表显示不正确
- Node.js:多个然后'It’执行顺序不正确
- Highcharts热图显示不正确
- Firefox使用JQuery返回不正确的JSON
- 尝试在两次迭代中警告同一选择器的值,在第一次迭代中得到正确的值,而在第二次迭代中获得不正确的值.为什么?
- Mongoose响应解析不正确
- 字符串中存在多个空格时,字数不正确
- 空格导致我的javascript显示不正确(修剪输出)