3

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?

4
  • element.classList = element.classList.replace... Commented Jul 6, 2019 at 13:24
  • @Clive That's wrong. Commented Jul 6, 2019 at 13:25
  • Is classList not a string? Fair enough then Commented Jul 6, 2019 at 13:26
  • @Clive no classList is a list and as it returns false it'd put className as false not as badge-success. Commented Jul 6, 2019 at 13:27

2 Answers 2

6

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.