Search code examples
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:

    • removeAttr doesn't take a function as argument. You have to pass the name of the attribute (a string).
    • There is no iteration happening over the attributes. For that you could use the this.attributes collection
    • The \w+ would allow letters to follow at the end. That's not what you stated in the question.
    • The regex lacks end-of-string markers, so it would also allow the pattern to occur somewhere in the middle of a long string with other characters.

    Also:

    • You don't need the RegExp constructor when you already have a regex literal
    • {1} is useless in a regex.
    • {0,} is equivalent to *
    • To check whether a string matches with a regex, you don't need 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>