I believe there is no jQuery magic for this, so here's my solution:
$('[class*=col]').each(function() {
this.className = $.grep(this.className.split(' '), function(el) {
return !/^col/.test(el);
}).join(' ');
});
Fiddle
Basically, it selects elements that have col
in their classes and iterate over them, iterating over their classes and removing those that begin with col
.
Or without regex:
$('[class*=col]').each(function() {
this.className = $.grep(this.className.split(' '), function(cl) {
return cl.lastIndexOf('col', 0);
}).join(' ');
});
Fiddle
Using a modified version of this answer. lastIndexOf
will return 0
if the class starts with col
which is a falsy value and thus grep
will remove it. If the class does not begin with col
, then -1
is returned which is a truthy value. You can use return cl.lastIndexOf('col', 0) !== 0;
for a bit extra readability as well.
Or with regex only:
$('[class*=col]').each(function() {
this.className = this.className.replace(/(^| )col[^ ]*/g, '');
});
Fiddle
Matches col
at beginning of the string or after a space, removes it together with all leading characters up to another space or end of the string.
Referece
jQuery.grep
- Finds the elements of an array which satisfy a filter function. The original array is not affected.
element.className
- gets and sets the value of the class
attribute of the specified element.
Of course, this selector is not optimal - if an element has foocol
the $('[class*=col]')
will select it, but the $.grep
/regex will not remove it as it does not begin with col
. I can't think of any better selector (there's no attribute selector to select a value beginning with a partial string in a space-separated list AFAIK), nevertheless this should suffice just fine.