Remove CSS classes by ReGexp, jQuery plugin

April 6, 2021

If your frontend is based on jQuery, then you often come across the need to remove CSS classes not by their full name, but by substring. Also, there is often a need to select all elements on the page whose classes contain a certain substring.
This article is a little cheat sheet, it shows how you can style classes removing operation can as a jQuery plugin, and then freely use them as needed.

Remove Classes

$.fn.removeClassRegEx = function(regex) {
  var classes = $(this).attr('class');
  if (!classes || !regex) return false;
  var classArray = [];
  classes = classes.split(' ');
  for (var i = 0, len = classes.length; i < len; i++)
    if (!classes[i].match(regex)) classArray.push(classes[i]);
  $(this).attr('class', classArray.join(' '));
};

Example : we have element that has set of classes – ‘test subclass-1 subclass-2’

<div class="test subclass-1 subclass2"></div>
$( '.test' ).removeClassRegEx( 'ub' );

Element will have only ‘test’ class.

Note that here you can use any valid JS RegExp constructs as an argument.

$( '.test' ).removeClassRegEx( /class(-)?[0-1]/ );

Result :

<div class="test"></div>

Select DOM elements by Classes substrings

It is much simlier, it is based on native CSS selectors

var set = $( '[class*="ubclas"]' );

This string returns all elements whose class name set contains one or more occurrences of the substring ‘ubclas’

Categorised in: js