I have a issue about strip HTML string.
I have a HTML string:
<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>
I want it become:
I have a dog<br/>
I have a cat too<br/>
I have a lion too
I have a issue about strip HTML string.
I have a HTML string:
<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>
I want it become:
I have a dog<br/>
I have a cat too<br/>
I have a lion too
Take the textContent
of each <p>
, then join by <br>
:
const input = `<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>`;
const doc = new DOMParser().parseFromString(input, 'text/html');
const output = [...doc.querySelectorAll('p')]
.map(p => p.textContent)
.join('<br>\n');
console.log(output);
Note that <br>
alone is sufficient.
You can use DOMParser
let str = `<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>`
let parser = new DOMParser()
let parsed = parser.parseFromString(str,'text/html')
let final = [...parsed.getElementsByTagName('p')].map(e=> e.textContent).join('<br/>')
console.log(final)
Note:- Regex is not a suitable tool for HTML parsing, but in case just for learning purpose you want to see how to do it with regex
let str = `<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>`
let op = str.split('\n').map(e=>e.replace(/<\/?p>/g,'')).join('<br/>')
console.log(op)