我有一个关于HTML字符串的问题,希望你们能帮助我。
我有一个HTML字符串:
<p>I have a dog</p>
<p>I have a cat too</p>
<p>I have a lion too</p>
我希望它成为:
I have a dog<br/>
I have a cat too<br/>
I have a lion too
答案 0 :(得分:1)
接受每个textContent
中的<p>
,然后加入<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);
请注意,仅<br>
个is sufficient。
答案 1 :(得分:1)
您可以使用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)
注意:-正则表达式不是用于HTML解析的合适工具,但是如果只是出于学习目的,您想了解如何使用正则表达式
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)