javascript - 在字符串的第一个字符之前计算空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25823914/
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
javascript - count spaces before first character of a string
提问by K3NN3TH
What is the best way to count how many spaces before the fist character of a string?
计算字符串第一个字符前有多少个空格的最佳方法是什么?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
回答by folkol
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT: You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
编辑:您可以搜索“非空白字符,或输入结束”以避免检查 -1。
' '.search(/\S|$/)
回答by JAAulde
Using the following regex:
使用以下正则表达式:
/^\s*/
in String.prototype.match()
will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
inString.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;
Remember that this will also match tab chars, each of which will count as one.
请记住,这也将匹配制表符,每个制表符都算作一个。
回答by iNikkz
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);
Here: I have used regular expressionto count the number of spacesbefore the fist character of a string.
这里:我使用正则表达式来计算字符串第一个字符之前的空格数。
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
回答by danday74
You could use trimLeft() as follows
您可以使用 trimLeft() 如下
myString.length - myString.trimLeft().length
Proof it works:
证明它有效:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
回答by maowtm
str.match(/^\s*/)[0].length
str is the string.
str 是字符串。