Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace class name using regular expression

Tags:

javascript

I'm trying to use classList.replace() with regular expression. My goal is replacing an expression like badge-something with an other value like badge-success.

I've tried this:

element.classList.replace(/badge-*/i, 'badge-success')

But it returns false and doesn't change nothing. What am I missing?

like image 862
Emilio Conte Avatar asked Apr 08 '26 21:04

Emilio Conte


1 Answers

Element.classList is a DOMTokenList (not a string).

DOMTokenList.replace takes two strings, not a regex. The first argument is the exact class name you want to replace. Patterns are not supported.

If you want to use regexes, you need a string:

element.className = element.className.replace(/(^|\s)badge-\S+/g, '$1badge-success');
like image 171
melpomene Avatar answered Apr 10 '26 11:04

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!