jQuery: How to remove classes from elements using a regular expression

jQuery's removeClass removes the given class string from an element collection. If you want to remove multiple/unknown classes matching a given pattern, you can do that.

For example, consider a DOM node for the following HTML. We'll reference it by $element below.

<div class="example is-amazing is-wonderful"></div>

Option A: Selecting classes, then removing them

You can iterate over existing classes, and select matching ones. The example below is ES6, on ES5 could write something similar using jQuery.grep.

let classes = Array.from($element.prop('classList'))
let existingModifiers = classes.filter(className => { return className.match(/^is-/) })

$layout.removeClass(existingModifiers.join(' '))

Note that classList is native DOM API and returns a DOMTokenList (not an Array) of element classes.

Option B: Using a matcher function

Since jQuery 1.4 (read: forever) you may pass a function that disects an element's class, and returns a string that will then be removed through the "classic" string approach. It's a bit awkward to use.

If we now want to remove those "is-" modifiers, and we don't know what they will be, we can remove them like so:

function modifierClassMatcher(index, className) {
  let matchedClasses = className.match(/(^|\s)is-\S+/g)
  return (matchedClasses || []).join('')
}

$element.removeClass(modifierClassMatcher)

The modifierClassMatcher function will look for any class names starting with "is-". We use ^ and \s to split the class attribute string and find all class names.
The function then returns the string to remove, in the example above " is-amazing is-wonderful".

Arne Hartherz Over 5 years ago