Kevin Pauli
Kevin Pauli

Reputation: 8915

Replace leading spaces with   in Javascript

I have text like the following, with embedded spaces that show indentation of some xml data:

&lt;Style id="KMLStyler"&gt;<br>
  &lt;IconStyle&gt;<br>
    &lt;colorMode&gt;normal&lt;/colorMode&gt;<br> 

I need to use Javascript to replace each LEADING space with

&nbsp;

so that it looks like this:

&lt;Style id="KMLStyler"&gt;<br>
&nbsp;&nbsp;&lt;IconStyle&gt;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&lt;colorMode&gt;normal&lt;/colorMode&gt;<br> 

I have tried a basic replace, but it is matching all spaces, not just the leading ones. I want to leave all the spaces alone except the leading ones. Any ideas?

Upvotes: 3

Views: 3513

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170288

JavaScript does not have the convenient \G (not even look-behinds), so there's no pure regex-solution for this AFAIK. How about something like this:

function foo() {
  var leadingSpaces = arguments[0].length;
  var str = '';
  while(leadingSpaces > 0) {
    str += '&nbsp;';
    leadingSpaces--;
  }
  return str;
}

var s = "   A B C";
print(s.replace(/^[ \t]+/mg, foo));

which produces:

&nbsp;&nbsp;&nbsp;A B C

Tested here: http://ideone.com/XzLCR

EDIT

Or do it with a anonymous inner function (is it called that?) as commented by glebm in the comments:

var s = "   A B C";
print(s.replace(/^[ \t]+/gm, function(x){ return new Array(x.length + 1).join('&nbsp;') }));

See that in action here: http://ideone.com/3JU52

Upvotes: 9

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143314

Use ^ to anchor your pattern at the beginning of the string, or if you'r dealing with a multiline string (ie: embedded newlines) add \n to your pattern. You will need to match the whole set of leading spaces at once, and then in the replacement check the length of what was matched to figure out how many nbsps to insert.

Upvotes: 1

Related Questions