-1

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
halfer
  • 19,824
  • 17
  • 99
  • 186
KitKit
  • 8,549
  • 12
  • 56
  • 82
  • what have you tried? You seem to have enough rep to understand how this works. Please add a [mcve] to your question – blurfus Jun 09 '19 at 05:45
  • 1
    Possible duplicate of [How to strip HTML tags from string in JavaScript?](https://stackoverflow.com/questions/5002111/how-to-strip-html-tags-from-string-in-javascript) – Shireesha Parampalli Jun 09 '19 at 05:46
  • I don't agree. That answer is old. Plus the given answer is much more elegant and precisely answers the question and sanitizes the input apparently. – Avin Kavish Jun 09 '19 at 05:48

2 Answers2

1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60