如何最好地计算字符串第一个字符之前有多少个空格?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
如何最好地计算字符串第一个字符之前有多少个空格?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
' foo'.search(/\S/); // 4, index of first non whitespace char
编辑: 您可以搜索“非空格字符或输入结尾”,以避免检查-1。
' '.search(/\S|$/)
' '.search(/\S|$/)
,这将考虑没有非空白字符的字符串。 - JAAuldevar offset = (' '+str.search(/\S|$/) -1;
- Wpigott使用以下正则表达式:
/^\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;
请记住,这也将匹配制表符,每个制表符将计为一个字符。
myString.length - myString.trimLeft().length
证明它有效:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
trimLeft
不是一个选项。只需使用上面的正则表达式解决方案。否则,这很棒。 - Sergiustr0 = '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
str.match(/^\s*/)[0].length
str是字符串。
let myString = " string";
let count_spaces = myString.length - myString.trim().length;
trimStart()
代替 trim()
呢? - Andy A.
/^\s+/
,并使用str0.match(/^\s+/)[0].length
进行计数。 - soktinpk