我有一个字符串,我想根据标签将其拆分
示例字符串:
var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'
我想根据标签分割字符串
预期结果:
splitString = ['<p>Hi my name is XXX</p>', '<p>Iam going to london</p>'];
提前感谢,应使用什么正则表达式来获得预期结果!
答案 0 :(得分:1)
没有正则表达式的方法(参见&#34的注释;为什么&#34;)。
.createElement()
).insertAdjacentHTML()
).querySelectorAll()
)Array.from()
).outerHTML
(.map()
)
function getParagraphs(htmlString) {
const div = document.createElement("div");
div.insertAdjacentHTML("beforeend", htmlString);
return Array.from(div.querySelectorAll("p"))
.filter(p => p.textContent !== "") // because of the lonely </p> at the end - optional
.map(p => p.outerHTML);
}
const str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>';
console.log(getParagraphs(str));
&#13;
答案 1 :(得分:0)
var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'
console.log( str.match(/<p>([^\<]*?)<\/p>/g) );