用正则表达式删除匹配的类 [英] Remove matching class with regex

查看:89
本文介绍了用正则表达式删除匹配的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在添加诸如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.

我做错了什么?

演示: http://jsfiddle.net/X5JxV/

推荐答案

c.match(/type-[a-z]{0,5}/)返回包含一个元素的数组.

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

您需要指定一个索引,即c.match(/type-[a-z]{0,5}/)[0],但首先应检查是否已发生匹配,否则将引发错误.

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
})

这篇关于用正则表达式删除匹配的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆