Emilio Conte
Emilio Conte

Reputation: 1145

replace class name using regular expression

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?

Upvotes: 3

Views: 1915

Answers (2)

Rajesh Kumar
Rajesh Kumar

Reputation: 51

classList.replace took string as an argument, so i think that is why it is not working. But you can achieve your goal by twisting your code little bit, repeat these steps

  1. first took all className of that element(using element.className)
  2. split those classes in array (using split function--- classname.split(' '))
  3. apply forEach loop on array and by using str.search('badge-') > -1, replace that className using element.classList.replace..........Simple little long but code will work definitly

. Thank you

Upvotes: 0

melpomene
melpomene

Reputation: 85767

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');

Upvotes: 6

Related Questions