views:

78

answers:

4

Hi,

I'm using regular expression to count the total spaces in a line (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

+1  A: 

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);
scunliffe
Something like this "Hello World<4 spaces>Test" would return '4' spaces,
Jimmy
@Jimmy in that case wombleton's second regex would return the right value
Justin Smith
+5  A: 

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

artlung
+3  A: 

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
wombleton
A: 

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

Orion Edwards