Spencer Gresoro
Spencer Gresoro

Reputation: 81

Removing all classes which match multiple partial class names in javascript

I use the removeClass function and pass it a callback to remove a class which matches a partial name

Here is my code

        $('.target').removeClass(function (index, className) {  
                return (className.match(/(^|\s)bg_\S+/g) || []).join(' ');
         });

What I want to do is remove all classes which start with bg_ AND any number of other possible matches.

I tried this

         $('.target').removeClass(function (index, className) {  
                return (className.match(/(^|\s)bg_\S+/g|/(^|\s)ag_\S+/g) || []).join(' ');
         });

to Remove anything that started with 'bg' AND 'ag', but it didn't work.

I appreciate the help, thank you.

Upvotes: 2

Views: 708

Answers (3)

Spencer Gresoro
Spencer Gresoro

Reputation: 81

Here is a wrapper solution I wrote with your help.

    // Wrapper for JQuery removeClass - pass a collection of elements and your own regex. This will strip out any classes matching the regex
var removeClassesByPartialMatch = function (targets, regex) { 

    regex = new RegExp(regex);   

    targets.removeClass((i, classes) => {
        var classes = classes.split(' ');
        return classes.filter(name => regex.test(name)).join(' ');
    });
}

Upvotes: 0

Barmar
Barmar

Reputation: 781255

Instead of trying to match the entire classname with a regexp, split it into separate classes and then filter that array.

$(".target").removeClass((i, className) => {
    var classList = className.split(" ");
    return classList.filter(class => /^(bg_|ag_)/.test(class)).join(" ");
});

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

Well, you can try this.

function removeClasses(){
      var classes = $(".target").attr("class").split(' ');
      console.log("Before removing:  ",$(".target").attr("class"))
      classes.forEach(e=> {
         var flag = e.substring(0, 3);
         
         if(flag === "AND" || flag.substring(0, 2) === "ag" || flag.substring(0, 2) === "bg"){
            $(".target").removeClass(e)
         }
      })
      console.log("After removing: ",$(".target").attr("class"))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="target bgAA AA ANDse agEF FF"></div>

<button onclick="removeClasses()">Remove</button>

Upvotes: 1

Related Questions