Javascript 计算字符串中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35849174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:16:23  来源:igfitidea点击:

Count Space(s) in a string

javascriptjquery

提问by cyber8200

I have a string "John Doe's iPhone6"

我有一个字符串 "John Doe's iPhone6"

Visually, I know that it contains 2 spaces.

在视觉上,我知道它包含 2 个空格。

How do I count spaces in a string in javascript ?

如何在javascript中计算字符串中的空格?

I've tried

我试过了

var input = this.value;
// console.log(input.count(' '));

回答by Mayki Nayki

Try this

尝试这个

var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount)

回答by elad.chen

Use RegExp:

使用正则表达式:

"John Doe's iPhone6".match(/([\s]+)/g).length

回答by Alvaro Joao

Use split and count them less 1 (-1):

使用 split 并将它们减去 1 ( -1):

var string = "John Doe's iPhone6";
string.split(" ").length-1