Reputation: 795
Remove wrapping <p tags from around <img tags with Javascript
Any ideas how to do this with Javascript and not php etc. The only example I can find online is with PHP
preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
Any help / guidance to refactor this into Javascript?
Many thanks.
Upvotes: 0
Views: 755
Reputation: 20953
If you want to remove the <p>
tag that only has <img>
tag as its child, you may try this regex:
<p\b[^<>\/]*>\s*(<img\b[^<>]*>)\s*<\/p>
$1
<p\b[^<>\/]*> // opening <p> tag
\s* // optional white spaces
(<img\b[^<>]*>) // <img> tag, and capture it in group 1
\s* // optional white spaces
<\/p> // closing </p> tag
Check the proof
const text = '<p class="text">test</p><p class="image"> <img src="vvv" /> </p>';
const regex = /<p\b[^<>\/]*>\s*(<img\b[^<>]*>)\s*<\/p>/g;
const result = text.replace(regex, '$1');
console.log(text);
console.log(result);
Upvotes: 2