0

I am removing classes from a HTML element according to some conditions. This is my regex pattern:

elem.className = elem.className.replace(/shake|progress|done/g, '');

but this pattern has a problem that if somebody adds another class say shaker, that will also be removed. so I changed the pattern to:

elem.className = elem.className.replace(/(^|\s)shake(\s|$)|(^|\s)progress(\s|$)|(^|\s)done(\s|$)/g, '');

now it removes only if the whole word matches. but now it removes the spaces around the word. I am not sure how to fix this issue. please help me with this.

4
  • 1
    This is not a job for regex. Interact with classList instead. Commented May 3, 2017 at 6:11
  • Can you give an accurate example of before and after, meaning string before and after regex applied Commented May 3, 2017 at 6:12
  • 3
    Derek has the right answer; but the technique to match whole words only with regexes might be worth mentioning anyway: Take a look at word boundary anchors. Commented May 3, 2017 at 6:15
  • For your regex question, use word boundaries: /\b(?:shake|progress|done)\b/ Commented May 3, 2017 at 8:55

3 Answers 3

3

This is not a job for regex. Interact with classList instead.

elem.classList.remove("shake", "progress", "done"); // removes all 3 class values
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that will work. But, maybe in some other case where I need to match the whole word. what should be the regex pattern.
0

classList.remove is the best way.

This answers your question:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="tt" class="eins zwei drei meins">ABC</div>
</body>
  <script>
    tt.className=tt.className.replace(/\beins|zwei|drei/g, '');
  </script>

</html>

Comments

0

I agree with others that classList is the way to go here, however you could accomplish this if you want to match whole words. Split className on space and filter any items that are in your list of classes to remove:

const classes = elem.className.split(' ');
const remove = ['shake', 'progress', 'done'];

elem.className = classes.filter(cls => !remove.includes(cls)).join(' ');

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.