Frage

I need to remove all classes from element starts with 'layout-'

I try:

var regex = new RegExp('\b' + 'layout-' + '.*?\b', 'g');
$(el)[0].className = $(el)[0].className.replace(regex, '');

but it doesn't work. Solution could be in jQuery. Any idea?

War es hilfreich?

Lösung

The RegExp you have posted in the question is not working because the \b is not escaped as \\b. Hence the actual RegExp is becoming /layout-.*?/g instead of /\blayout-.*?\b/g. Doing the below change would work.

var regex = new RegExp('\\b' + 'layout-' + '.+?\\b', 'g');

You can also try like the below. This removes all classes that are like layout-X

var regex = /(\s)*(layout-.*?)(?=\s)/g; 
$('#test')[0].className = $('#test')[0].className.replace(regex, '');

Demo Fiddle

Input: class=sample layout-10 layout-9 sample1 slayout

Output: class=sample sample1 slayout

RegExp Explained:

\s - Any whitespace character

(layout-.*?) - Capture all values like layout-X where X can be any character any number of times

(?=\s) - Look ahead upto the next whitespace character (meaning till end of word)


As pointed out by musefan in the comments var regex = /\blayout-.+?\b/g; will also do the job.

Andere Tipps

$("[class^='layout-']").removeAttr('class');

reference attribute-starts-with-selector

removeAttr

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top