Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

375
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda