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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With