I want to remove attribute tags that start with a letter "z" followed by any digits ("z#").
But I have errors as you can see when running this snippet:
$("#main article").each(function(){
var DE = new RegExp(/z{1}(\d{0,})\w+/);
$(this).removeAttr(function (){
return (this.match(DE));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="main">
<article z1 > AAA </article>
<article z2 > BBB </article>
<article z3 > CCC </article>
<article z101> DDD </article>
<article z102> EEE </article>
<article z103> FFF </article>
</section>
What is the problem?
There are a few issues in your attempt:
removeAttr
doesn't take a function as argument. You have to pass the name of the attribute (a string).this.attributes
collection\w+
would allow letters to follow at the end. That's not what you stated in the question.Also:
RegExp
constructor when you already have a regex literal{1}
is useless in a regex.{0,}
is equivalent to *
match
(which returns an array), but can better use test
.$("#main article").each(function(i, article) {
$(this.attributes).each(function () {
if (/^z\d*$/.test(this.name)) $(article).removeAttr(this.name);
});
});
console.log($("#main").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="main">
<article z1 > AAA </article>
<article z2 > BBB </article>
<article z3 > CCC </article>
<article z101> DDD </article>
<article z102> EEE </article>
<article z103> FFF </article>
</section>