javascript - 计算字符串第一个字符前的空格

K3N*_*3TH 14 javascript regex string

在字符串的第一个字符之前计算多少个空格的最佳方法是什么?

str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = '  twospaces';
Run Code Online (Sandbox Code Playgroud)

fol*_*kol 38

使用 String.prototype.search

'    foo'.search(/\S/);  // 4, index of first non whitespace char
Run Code Online (Sandbox Code Playgroud)

编辑:您可以搜索"非空白字符,或输入结束",以避免检查-1.

'    '.search(/\S|$/)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个。它确实要求至少出现一个非空白字符,但它很好很干净。我建议添加以下内容:`' '.search(/\S|$/)` 它将解释没有非空白字符的字符串。 (3认同)

dan*_*y74 6

您可以使用 trimLeft() 如下

myString.length - myString.trimLeft().length
Run Code Online (Sandbox Code Playgroud)

证明它有效:

myString.length - myString.trimLeft().length
Run Code Online (Sandbox Code Playgroud)

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft


JAA*_*lde 5

使用以下正则表达式:

/^\s*/
Run Code Online (Sandbox Code Playgroud)

in 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;
Run Code Online (Sandbox Code Playgroud)

请记住,这也会匹配制表符,每个制表符都会计为一个.


iNi*_*kkz 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);
Run Code Online (Sandbox Code Playgroud)

这里:我使用正则表达式来计算字符串第一个字符之前的空格数。

^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
Run Code Online (Sandbox Code Playgroud)