最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Replace leading spaces with   in Javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Dec 23, 2010 at 20:11 Kevin PauliKevin Pauli 8,91515 gold badges54 silver badges72 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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./XzLCR

EDIT

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

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./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)

  1. 暂无评论