Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
Kevin Pauli Avatar asked Aug 31 '26 15:08

Kevin Pauli


2 Answers

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

like image 191
Bart Kiers Avatar answered Sep 03 '26 03:09

Bart Kiers


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.

like image 24
Laurence Gonsalves Avatar answered Sep 03 '26 04:09

Laurence Gonsalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!