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

428
Views
Regex para eliminar todos los atributos de las etiquetas html anidadas - Javascript

Quiero eliminar los atributos de la etiqueta html usando expresiones regulares. Podría ser cualquier elemento html y permitir elementos anidados como:

 <div fadeout"="" style="margin:0px;" class="xyz"> <img src="abc.jpg" alt="" /> <p style="margin-bottom:10px;"> The event is celebrating its 50th anniversary K&ouml;&nbsp; <a style="margin:0px;" href="http://www.germany.travel/">exhibition grounds in Cologne</a>. </p> <p style="padding:0px;"></p> <p style="color:black;"> <strong>A festival for art lovers</strong> </p> </div>

o podría ser como

<span style="margin: 0;"><p class="abc"> Test text</p></span>

por razones de seguridad, es necesario eliminar atributos

Lo que he tratado de eliminar

 s/(<\w+)\s+[^>]*/$1/ <*\b[^<]*>(?:[^<]+(?:<(?!\/?div\b)[^<]*)*|(?R))*<\/*>\s* <([az][a-z0-9]*)[^>]*?(\/?)>

pero no funciona

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Regex no debe usarse para analizar HTML.

En su lugar, debe usar un DOMParser para analizar la cadena, recorrer los atributos de cada elemento y usar Element.removeAttribute :

 const str = `<div fadeout"="" style="margin:0px;" class="xyz"> <img src="abc.jpg" alt="" /> <p style="margin-bottom:10px;"> The event is celebrating its 50th anniversary K&ouml;&nbsp; <a style="margin:0px;" href="http://www.germany.travel/">exhibition grounds in Cologne</a>. </p> <p style="padding:0px;"></p> <p style="color:black;"> <strong>A festival for art lovers</strong> </p> </div>` function stripAttributes(html){ const parsed = new DOMParser().parseFromString(html, 'text/html') parsed.body.querySelectorAll('*').forEach(elem => [...elem.attributes].forEach(attr => elem.removeAttribute(attr.name))) return parsed.body.innerHTML; } console.log(stripAttributes(str))

about 4 years ago · Juan Pablo Isaza Report

0

Le aconsejaría que no use expresiones regulares en esta situación, pero si no tiene otra opción, tal vez esté buscando algo como esto:

 /<\s*([az][a-z0-9]*)\s.*?>/gi
about 4 years ago · Juan Pablo Isaza Report

0

¡Lo bueno de trabajar con el DOM es que tiene un conjunto completo de herramientas disponibles que fueron diseñadas específicamente para manipular un DOM! Y, sin embargo, las personas insisten en tratar este complejo formato de datos estructurados como si fuera solo una cadena tonta y comienzan a piratearlo con expresiones regulares.

Utilice la herramienta adecuada para el trabajo.

 function removeAttributesRecursively(el) { Array.from(el.attributes).forEach(function(attr) { // you'll probably want to include extra logic here to // preserve some attributes (a href, img src, etc) // instead of blindly removing all of them el.removeAttribute(attr.name); }); // recurse: Array.from(el.children).forEach(function(child) { removeAttributesRecursively(child) }) } const root = document.getElementById('input'); removeAttributesRecursively(root) console.log(root.innerHTML)
 <div id="input"> <div fadeout="" style="margin:0px;" class="xyz"> <img src="abc.jpg" alt="" /> <p style="margin-bottom:10px;"> The event is celebrating its 50th anniversary K&ouml;&nbsp; <a style="margin:0px;" href="http://www.germany.travel/">exhibition grounds in Cologne</a>. </p> <p style="padding:0px;"></p> <p style="color:black;"> <strong>A festival for art lovers</strong> </p> </div> </div>

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!