CodeMoose
CodeMoose

Reputation: 3025

jQuery - regexp selecting and removeClass()?

I've been given several auto-generated HTML docs that are thousands of lines long, and I need to clean up the source. Mostly need to remove classnames like "table-col-##". This is a two-step problem:

  1. Select any and all classes that have table-col-##, where ## is an integer between 0-999
  2. Remove the matching class from the element, without removing any of the other classes

So it boils down to: I need a way, if possible, to use regexps in $() selectors, and then either to obtain the selected class in each() - or apply the regexp to $.removeClass(). Can anyone point me in the right direction?

UPDATE: Is there any sort of $.removeClass([selected]) functionality? That seems like the easiest way to solve the second part.

Upvotes: 10

Views: 12323

Answers (7)

DBR
DBR

Reputation: 165

In case someone is searching for an alternative regex-based solution:

const classes = $(selector).attr('class');
const newClasses = classes.replace(regex, yourNewClass[or part]);
$(selector).removeClass().attr('class', newClasses);

I hope this proves helpful.
In my scenario, I utilize this method to locate a class and substitute the attached number:

const target = 2;
const bodyClasses = $body.attr('class');
const newBodyClasses  = bodyClasses .replace(/page-\d/, `s${target}`);
$body.removeClass().attr('class', newBodyClasses  );

Upvotes: 0

ChrisHiebert
ChrisHiebert

Reputation: 200

You can do this without the need to split the class names into an array. Let the regular expression do all the work.

For each element found, remove all the classes that match the regular expression.

$("[class^='table-col-']").removeClass( function() {
    return (this.className.match(/\b(table-col-\d{1,3})\b/g) || []).join(' ');
})

Upvotes: 6

ronen
ronen

Reputation: 2598

This question is now old, but if anybody else comes across it...

I created a simple plugin jquery.classMatch which provides

$(selector).hasClassMatch(regexp)
$(selector).removeClassMatch(regexp)

Upvotes: 0

neiker
neiker

Reputation: 8991

Try this:

$.fn.removeClassRegExp = function (regexp) {
    if(regexp && (typeof regexp==='string' || typeof regexp==='object')) {
        regexp = typeof regexp === 'string' ? regexp = new RegExp(regexp) : regexp;
        $(this).each(function () {
            $(this).removeClass(function(i,c) { 
                var classes = [];
                $.each(c.split(' '), function(i,c) {
                    if(regexp.test(c)) { classes.push(c); }
                });
                return classes.join(' ');
            });
        });
    }
    return this;
};

Live: http://jsfiddle.net/Z3D6P/

Upvotes: 1

Aditya Singh
Aditya Singh

Reputation: 9612

Try this out:

http://jsfiddle.net/adiioo7/AmK4a/1/

JS:-

$(function () {
    $("div").filter(function() {
        return this.className.match(/table-col-\d{0,3}/);
    }).each(function(){
        var classToRemove=this.className.match(/table-col-\d{0,2}/)[0];
        $(this).removeClass(classToRemove);
    });
});

Sample HTML:-

<div class="table-col-0 temp">Test0</div>
<div class="table-col-99">Test99</div>
<div class="table-col-999">Test999</div>

Output HTML:-

<div class="temp">Test0</div>
<div class="">Test99</div>
<div class="table-col-999">Test999</div>

Upvotes: 1

Alex Pacurar
Alex Pacurar

Reputation: 5861

try

var className = 'table-col-';
$('[class^='+className+']').removeClass(function(index, class) {
    return class.indexOf(className) == 0;
});

see http://api.jquery.com/removeClass/ and http://api.jquery.com/attribute-starts-with-selector/

edited:

var className = 'table-col-';
$('[class^='+className+']').removeClass(function(index, c) {
    var elem = $(this);
    $(c.split(' ')).each(function() {
        var c = this.trim();
        if(this.indexOf(className)==0) {
            elem.removeClass(c);
        }
    });
});

Upvotes: 0

Jakub Kotrs
Jakub Kotrs

Reputation: 6244

If only numbers are acceptable, but there can be other characters too, I would start with something like this (not tested, but edited with help from comments):

$("[class^='table-col-']").removeClass( function() { /* Matches even table-col-row */
     var toReturn = '',
         classes = this.className.split(' ');
     for(var i = 0; i < classes.length; i++ ) {
         if( /table-col-\d{1,3}/.test( classes[i] ) ) { /* Filters */
             toReturn += classes[i] +' ';
         }
     }
     return toReturn ; /* Returns all classes to be removed */
});

Upvotes: 21

Related Questions