Remove matching class with regex

2019-09-09 10:46发布

问题:

I want to remove matching class like type-one before adding new class like type-two

HTML :

<div class="demo test">
    <span>One</span>
    <span>Two</span>
    <span>Three</span>
</div>

jQuery :

$(document).on("click" ,".demo > span", function(){
        $(this).addClass("active").siblings().removeClass("active");


        $(this).parents(".demo").removeClass(function(i, c){
            return c.match(/type-[a-z]{0,5}/);
        })

        $(this).parents(".demo").addClass("type-"+$(this).text().toLowerCase());

})

My code is still adding and adding , cant remove the old matching class.

What I am doing wrong ?

Demo : http://jsfiddle.net/X5JxV/

回答1:

c.match(/type-[a-z]{0,5}/) is returning an array with one element.

You need to specify an index, i.e. c.match(/type-[a-z]{0,5}/)[0], but first you should check that a match as occurred, otherwise an error will be thrown.

$(this).parents(".demo").removeClass(function(i, c){
    var m = c.match(/type-[a-z]{0,5}/);
    return m ? m[0] : m
})


回答2:

What about this:

$(document).on("click" ,".demo > span", function(){
    $(this).addClass("active").siblings().removeClass("active");
    $(this).parents(".demo").removeClass().addClass("demo type-" + $(this).text().toLowerCase());
});

Here we remove all class names including demo and then reset it again with new type-xxx class.