• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

19
Views
With Javascript and regex remove wrapping <p tags from around <img tags

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.

about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

If you want to remove the <p> tag that only has <img> tag as its child, you may try this regex:

  • Regex
<p\b[^<>\/]*>\s*(<img\b[^<>]*>)\s*<\/p>
  • Substitution
$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);

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.