So, I have some text that looks like:
<div class="content__main">
<p>This is some text<br>
This is another line<br>
Third line goes here<br>
How about one more</p>
</div>
What I’d like to do is use JavaScript or jQuery to find the <br>
tags and replace them with </p><p>
tags. The content is auto-generated, so I can’t just add it myself.
I’d like it to look like:
<div class="content__main">
<p>This is some text</p>
<p>This is another line</p>
<p>Third line goes here</p>
<p>How about one more</p>
</div>
I tried:
<script type="text/javascript">
$(function(){
$('.content__main').replace(/<br>\\*/g,"</p><p>"));
});
</script>
But this doesn’t seem to do anything, I think I’m pretty close though, can anyone shed some light on this for me?
Thanks,
Josh
>Solution :
Simple, unsafe way
You could just do the replace
on the innerHTML
and set that to the element.
const d = document.querySelector('.content__main');
d.innerHTML = d.innerHTML.replace(/<br>\\*/g,"</p><p>");
<div class="content__main">
<p>This is some text<br>
This is another line<br>
Third line goes here<br>
How about one more</p>
</div>
Safer way to prevent un-closed tags
A more safe way of doing this, to prevent missing a closing tag is to:
- Get the
innerHTML
- Split on newlines
- For each line;
- Remove all the tags
trim()
the spaces- Create a
p
and add the text - Insert that to the original
div
const d = document.querySelector('.content__main');
const old = d.innerHTML;
d.innerHTML = '';
for (let line of old.split("\n")) {
let cleaned = line.replace(/<\/?[^>]+(>|$)/g, "").trim();
if (cleaned !== '') {
let newE = document.createElement('p')
newE.innerHTML = cleaned;
d.appendChild(newE);
}
}
<div class="content__main">
<p>This is some text<br>
This is another line
Third line goes here<br>
How about one more</p>
</div>