hvgotcodes
hvgotcodes

Reputation: 120318

javascript regex to count whitespace characters

Can I use a javascript regex to count the number of whitespace characters before the first text character in the string? I only care if there are 0, 1, and 2+.

My current working solution is to have three regexes and just use match to determine the 0,1, or 2+ category(separate pattern for each), but Im looking for a more elegant solution.

Is it even possible to count patterns with regex? I could use a non-greedy grouping and count the length I guess....

Upvotes: 9

Views: 21080

Answers (6)

kennebec
kennebec

Reputation: 104850

You could find the index of the first non-space character in the string, which is the same as the number of leading white space characters.

t.search(/\S/);

If you insist you can limit the return to 0, 1 or 2 with Math.min(t.search(/\S/), 2);

If there are no non-space characters the return will be -1....

Upvotes: 2

jfriend00
jfriend00

Reputation: 708146

I'm not sure I'd use a regex in real life for this job, but you can match them in a capture and the see their length:

function countLeadingSpaces(str) {
    return(str.match(/^(\s*)/)[1].length;
}

A non regex way designed for speed (pretty much anything is fast compared to a regex):

function countLeadingSpaces2(str) {
    for (var i = 0; i < str.length; i++) {
        if (str[i] != " " && str[i] != "\t") {
            return(i);
        }
    }
    return(str.length);
}

Upvotes: 3

Enki
Enki

Reputation: 573

You can just do :

"   aaa".replace(/^(\s*).*$/,"$1").length

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 882726

Why not just use a capture group and check the length:

<html>
    <head>
    </head>
    <body>
        <script language="javascript">
            var myStr = "  hello";
            var myRe = /^(\s*)(.*)$/;
            var match = myRe.exec(myStr);
            alert(match[1].length);  // gives 2
            alert(match[2]);         // gives "hello"
        </script>
    </body>
</html

This can be followed by code that acts on your three cases, a length of 0, 1 or otherwise, and acts on the rest of the string.

You should treat regexes as the tool they are, not as an entire toolbox.

Upvotes: 0

aroth
aroth

Reputation: 54854

This should do the job:

string.split(/[^ \t\r\n]/)[0].length;

Example: http://jsfiddle.net/Nc3SS/1/

Upvotes: 0

SLaks
SLaks

Reputation: 888273

"     a".match(/^\s{0,2}/)[0].length

This regex matches between 0 and 2 whitespace characters at the beginning of a string.

Upvotes: 8

Related Questions