Insert multiple line breaks into a JavaScript string (regex) (CodeMirror)
Posted
by
PJH
on Stack Overflow
See other posts from Stack Overflow
or by PJH
Published on 2012-06-04T16:10:19Z
Indexed on
2012/06/04
16:42 UTC
Read the original article
Hit count: 367
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 
 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:
<PhoneNumber>
or
</PhoneNumber>
So basically need to insert a \n
after every >
that is a closing tag or a beginning tag that contains children tags.
© Stack Overflow or respective owner