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:
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.
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 */
});
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(' ');
})
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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With