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
2 Answers
Reset to default 3An 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
评论列表(0条)