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ö <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
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ö <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))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¡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ö <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>