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
' 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)
您可以使用 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
使用以下正则表达式:
/^\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)
请记住,这也会匹配制表符,每个制表符都会计为一个.
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)