JavaScript - 如何计算字符串中第一个字符之前的空格数量?

29

如何最好地计算字符串第一个字符之前有多少个空格?

str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = '  twospaces';

出于好奇,你为什么想要计算空格?你知道右侧修剪吗? - rybo111
我有一个文本框用于快速编辑JSON字符串,我需要知道字符串开始前有多少个空格,以便确定它在对象中的位置。 - K3NN3TH
您可以使用正则表达式/^\s+/,并使用str0.match(/^\s+/)[0].length进行计数。 - soktinpk
尝试使用jQuery并结合下面的建议解决方案添加ltrim函数。参考链接:http://www.somacon.com/p355.php - Sanket Tarun Shah
6个回答

63

使用String.prototype.search

'    foo'.search(/\S/);  // 4, index of first non whitespace char

编辑: 您可以搜索“非空格字符或输入结尾”,以避免检查-1。

'    '.search(/\S|$/)

4
我喜欢这个。它需要至少一个非空白字符,但很简洁明了。我建议增加 ' '.search(/\S|$/),这将考虑没有非空白字符的字符串。 - JAAulde
如果\S没有匹配,它会返回-1。 - folkol
根据问题提出者的需求,不论我的贡献如何,我更喜欢这个答案。很好的思考。 - JAAulde
1
是的,这是一个不错的方法来处理它。我会更新答案。 - folkol
不会有全空格的情况,但了解这一点仍然很好。 - K3NN3TH
你可以使用以下代码处理所有变化: var offset = (' '+str.search(/\S|$/) -1; - Wpigott

10

使用以下正则表达式:

/^\s*/

String.prototype.match()方法返回一个数组,其中只有一个元素,该元素表示字符串开头的空格数量。

pttrn = /^\s*/;

str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;

str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;

str2 = '  twospaces';
len2 = str2.match(pttrn)[0].length;

请记住,这也将匹配制表符,每个制表符将计为一个字符。


1
需要等待6分钟才能回答。 - K3NN3TH
1
看一下我在@folkol答案下的评论,然后接受那个答案。我喜欢那个解决方案更好。你可以根据你的情况和需求确定是否需要我的补充,但总体上它更干净。 - JAAulde
1
是的,找到索引确实很棒。我再也不会看字符串了。 - K3NN3TH

8

1
如果你需要支持IE,trimLeft不是一个选项。只需使用上面的正则表达式解决方案。否则,这很棒。 - Sergiu

5
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = '  twospaces';

arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);

arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);

arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);

这里:

我使用了正则表达式计算字符串首字符之前的空格数

^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group

0
str.match(/^\s*/)[0].length

str是字符串。


0
有点晚了,但是为了提供一个不同的答案。
let myString     = "     string";
let count_spaces = myString.length - myString.trim().length;

请注意,如果字符串末尾有空格,它们也会被添加。

好主意。但是明确要求计算字符串开头的空格,那么为什么不使用 trimStart() 代替 trim() 呢? - Andy A.
是的!你说得对。它也可以用于其他情况,当然还有 trimEnd()。 - David Cervera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接