简体   繁体   中英

Insert multiple line breaks into a JavaScript string (regex) (CodeMirror)

I have a few strings and I would like to insert some line breaks into them at certain points.

I figured out a few of the logistics but as a whole I can't seem to crack this problem, probably because I have limited experience with regex.

Basically I have a long string of XML tags that is all on one line. I want to add line breaks at certain points to get the data more formatted and looking nice. I am using CodeMirror to display this data on a webpage but for some reason its all on line #1.

So I need to go from something like this:

<Sample><Name></Name><PhoneNumber><AreaCode></AreaCode><Number></Number></PhoneNumber></Sample>

To something like this:

<Sample>
  <Name></Name>
  <PhoneNumber>
    <AreaCode></AreaCode>
    <Number></Number>
  </PhoneNumber>
</Sample>

CodeMirror will take care of the rest of the formatting all I need to do is insert the line breaks in the right spot using regex or a loop of some sort. The Tags will or can change so I am guessing regex has to be used.

I have had success inserting line breaks with \\n and &#xD but can't seem to get regex to detect the proper locations.

Any help would be greatly appreciated. Thanks.

UPDATE I overlooked this but the brackets are in fact being sent as < and >

So example tag would look like:

&lt;PhoneNumber&gt;

or

&lt;/PhoneNumber&gt;

So basically need to insert a \\n after every &gt; that is a closing tag or a beginning tag that contains children tags.

Try this regex pattern:

  >\s*<(?!/)

Replacement string : >\\n<

UPDATE:

&gt;\s*&lt;(?!/)

There be dragons here.

I'd like to point you to a very similar question answered awhile ago that does a good job of explaining why you should NOT try to parse XML yourself unless you REALLY know what you're doing.

Use an XML deserializer if you want to get nice line breaks and that sort of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM