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.