1

I have a string like

str = "< p>line 1< br>< /p>< p>lin2< br>< /p>< h1>line 3< br>< /h1>";

and i need to swap < br> with their immediate next closing tags which in the above case are < /p>, < /p> and < /h1>

so final str required is:

finalStr = "< p>line 1< /p>< br>< p>lin2< /p>< br>< h1>line 3< /h1>< br>";

I tried creating regex but was not successful. Can anyone guide how in this case i can create regex and swap the occurrences of br with the next closing tags only using JS ? PS: i have added extra space in all tags so that the html editor can ignore reading them as tags

3 Answers 3

2

you can try:

"< p>line 1< br>< /p>< p>lin2< br>< /p>< h1>line 3< br>< /h1>".replace(/(< br>)(< \/[\w\d]*>)/g,'$2$1')
//"< p>line 1< /p>< br>< p>lin2< /p>< br>< h1>line 3< /h1>< br>"
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, i do not have good understand of regex that is why needed a quick help..will learn more about creating regex
1

It is not a good idea to do dom manipulation using regex, instead you can try something like

str = "<p>line 1<br></p><p>lin2<br></p><h1>line 3<br></h1>";
var div = document.createElement('div');
div.innerHTML = str;

var brs = div.querySelectorAll('br');
[].forEach.call(brs, function(br) {
  br.parentNode.parentNode.insertBefore(br, br.parentNode.nextSibling)
});
snippet.log(div.innerHTML)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

1 Comment

I agree with you regarding dom manipulation, but actually intention was not to impact DOM, it was just to create some string out of DOM elements keeping DOM as it is.
1

Simply try this

var str = "< p>line 1< br>< /p>< p>lin2< br>< /p>< h1>line 3< br>< /h1>";
var vca = str.replace(/<\sbr>(<\s\/\w>)/,"$1<br>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.