开发者

Replace leading spaces with   in Javascript

开发者 https://www.devze.com 2023-02-01 04:27 出处:网络
I have text like the following, with embedded spaces that show indentation of some xml data: &lt;Style id=\"KMLStyler\"&gt;<br>

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;no开发者_如何学编程rmal&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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消