最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - quantity of white spaces left of a string jQuery - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 8

Using 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.

发布评论

评论列表(0)

  1. 暂无评论