Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

371
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 4 years 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 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!