javascript - Regex to split string based on html tags - Stack Overflow

I have a string where i want to split it based on the tagsSample string:var str = '<p>Hi my

I have a string where i want to split it based on the tags

Sample string:

var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'

I want to split the string based on their tags

Expected result:

splitString = ['<p>Hi my name is XXX</p>', '<p>Iam going to london</p>'];

What regex should be used to get the expected result, thanks in advance!

I have a string where i want to split it based on the tags

Sample string:

var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'

I want to split the string based on their tags

Expected result:

splitString = ['<p>Hi my name is XXX</p>', '<p>Iam going to london</p>'];

What regex should be used to get the expected result, thanks in advance!

Share Improve this question asked Mar 26, 2018 at 11:09 Taha MdTaha Md 212 silver badges5 bronze badges 4
  • You just killed an unicorn while trying to parse html with regex. – Mike Doe Commented Mar 26, 2018 at 11:10
  • 2 Read this question first. – axiac Commented Mar 26, 2018 at 11:12
  • This is called parsing. Don't use Regular Expressions for parsing HTML documents. Use a DOM parser instead. – revo Commented Mar 26, 2018 at 11:17
  • Possible duplicate of RegEx match open tags except XHTML self-contained tags – Sascha Commented Mar 26, 2018 at 11:23
Add a ment  | 

2 Answers 2

Reset to default 3

An approach without a regular expression (see the ments for the "why").

  • Create a temporary container (.createElement())
  • Insert the markup and let the browser handle the parsing and fixing of maybe invalid markup (.insertAdjacentHTML())
  • Get the nodes you want (.querySelectorAll())
  • Convert the HTMLCollection into an actual array for easier handling (Array.from())
  • Get the .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));

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) );

see: https://regex101./r/mtPZVg/1

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744801116a4594495.html

相关推荐

  • javascript - Regex to split string based on html tags - Stack Overflow

    I have a string where i want to split it based on the tagsSample string:var str = '<p>Hi my

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信