jqueryregexattr

How to remove HTML attribute starting with letter + number?


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?


Solution

  • There are a few issues in your attempt:

    Also:

    $("#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>