开发者

Reading a line backwards

I'm using regular expression to count the total spaces in a l开发者_运维百科ine (first occurrence).

match(/^\s*/)[0].length;

However this reads it from the start to end, How can I read it from end to start.

Thanks


You can do this:

function reverse(str) {
    return str.split('').reverse().join('');
}

To use it:

var str = 'Hello World';
alert(reverse(str));

How it works, we split the string by an empty character to turn it into an array, then we reverse the order of the array, then we join it all back together, using no character as the glue. So we get alerted dlroW olleH


Are you trying to find the number of trailing spaces on a line?

s.match(/\s*$/)[0].length;

Or last spaces found, even if there's something else trailing:

s.match(/(\s*)[^\s]*$/)[1].length


do you just want to know how many chars there is before the space? If so, does this not suit your needs.

var str = 'The quick brown fox jumps';

var first = str.indexOf(' ');
var last = str.lastIndexOf(' ');

alert('first space is at: ' + first + ' and last space is at: ' + last);


I'm using regular expression to count the total spaces in a line

Then why do you care about which way it counts? "aaa" contains 3 a's whether I start from the first or last one. 3 is still 3...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜