正则表达式基于html标签分割字符串

时间:2018-03-26 11:09:29

标签: javascript regex split

我有一个字符串,我想根据标签将其拆分

示例字符串:

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>'];

提前感谢,应使用什么正则表达式来获得预期结果!

2 个答案:

答案 0 :(得分:1)

没有正则表达式的方法(参见&#34的注释;为什么&#34;)。

&#13;
&#13;
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;
&#13;
&#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) );

请参阅:https://regex101.com/r/mtPZVg/1