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.