1.21 gigawatts
1.21 gigawatts

Reputation: 17880

Get all the whitespace except new lines from the start of a line until any content?

I'm trying to get all the white space leading up to any content on a line. I'm not getting the results with my RegExp:

var oneLineOfText = "           Hello World";
var whiteSpace = oneLineOfText.replace(/([\t| ]*).*$/, "$1");

Expected results (inside of quotes):

"           "

NB: In the expected results it looks like the tab characters are getting converted to space characters.

Note: I do not want to match new lines. I'm trying to get the indentation amount from the string. If there is a new line or a few new lines then I'm going to assume no indentation.

Upvotes: 0

Views: 99

Answers (1)

ndnenkov
ndnenkov

Reputation: 36110

^[ \t]*
  • ^ - from the beginning of the line
  • [ \t]* - as many spaces or tabs as possible

var oneLineOfText = "           Hello World";
var whiteSpace    = oneLineOfText.match(/^[ \t]*/)[0];
whiteSpace.length // => 11


If you want to match a multiline string you will have to add appropriate gm modifiers:

var multilineText = "   foo\n     bar";
var whiteSpaces   = multilineText.match(/^[ \t]*/gm);
whiteSpaces[0].length // => 3
whiteSpaces[1].length // => 5

Upvotes: 3

Related Questions