Javascript regex for counting whitespace

Is it possible to use javascript regular expression to count the number of whitespace before the first text character in a string? I don't care if there are 0, 1 and 2 +.

My current working solution is to have three regular expressions and just use a match to define a category of 0.1 or 2+ (a separate template for each), but Im looking for a more elegant solution.

Is it even possible to read regular expression patterns? I could use inanimate grouping and count the length, I think ....

+7
source share
6 answers
" a".match(/^\s{0,2}/)[0].length 

This regular expression matches between 0 and 2 space characters at the beginning of a line.

+6
source

You can simply do:

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

I'm not sure that I will use regular expression in real life for this work, but you can match them in a capture and see their length:

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

Not a regular way designed for speed (almost everything is fast compared to a regular expression):

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

This should complete the task:

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

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

+1
source

You can find the index of the first non-spatial character in the string, which matches the number of leading space characters.

 t.search(/\S/); 

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

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

+1
source

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 may be followed by code that acts on your three cases, length 0, 1, or otherwise, and acts on the rest of the line.

You should treat regular expressions as a tool, not a whole set of tools.

0
source

All Articles