admin管理员组文章数量:1356824
I need to count the white spaces left of a string with jQuery.
For example:
String: " Hello how are you? " will have 4 white spaces at its left!
How can i get that with jQuery?
thanks.
I need to count the white spaces left of a string with jQuery.
For example:
String: " Hello how are you? " will have 4 white spaces at its left!
How can i get that with jQuery?
thanks.
Share Improve this question edited Feb 22, 2012 at 21:28 JaredPar 756k151 gold badges1.3k silver badges1.5k bronze badges asked Feb 22, 2012 at 21:26 euthereuther 2,6865 gold badges25 silver badges36 bronze badges3 Answers
Reset to default 8Using regexp in plain old JavaScript:
var spacesOnLeft = myStr.match(/^ */)[0].length
No loops involved. :)
This is something that's doable with plain old javascript.
function countLeftBlanks(arg) {
var i = 0;
while (i < arg.length && arg[i] === ' ') {
i++;
}
return i;
}
If we're using RegExp, the below might be a better cross-environment solution:
var spacesOnLeft = ( myStr.match(/^ */) || [[]] )[0].length;
The above stops a TypeError from being thrown in certain environments when the result of match
is null
. In the official ECMAScript Language Specification, the match
method states that:
If n = 0, then return null.
Despite this, most modern browsers seem to return an array with an empty string in it. In some environments, however, the ECMAScript definition is honoured, and a TypeError will be thrown if attempting to access matched[0]
. The NodeJS environment is a good example of this.
本文标签: javascriptquantity of white spaces left of a string jQueryStack Overflow
版权声明:本文标题:javascript - quantity of white spaces left of a string jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744071288a2585933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论