1

(Pure javascript only, please!)

I want to create a helper function that removes a single class from a div with several classes. I'm imagining a function as follows:

function remove_class(div, klass) {
    div.className = div.className.replace( /(?:^|\s)active(?!\S)/ , '' );
}

The class removed here is active. However, how can I remove any class name, ie. one passed as the klass variable?

5
  • Why not use classList? The MDN page even has a shim for browser compatibility Commented Sep 30, 2013 at 1:27
  • Limited compatibility is why. :) And this is not a duplicate - it's a much more specific question. Commented Sep 30, 2013 at 1:35
  • 1
    It's compatible down to IE8 with the shim. And yes, this question is an exact duplicate of the other one. The answers are the same too Commented Sep 30, 2013 at 1:38
  • No it isn't, because I didn't understand the other answers. I've looked it over several times, in fact. The answer I got here was easy to understand. So thanks for voting to close this question, on behalf of other to come after me. Commented Sep 30, 2013 at 1:40
  • No offense, but I think there is a misunderstanding. If the answers are not easy to understand it is not advisable to duplicate the question. Instead you can ask your question as a comment at the initial question. So Phil is right and you have duplicated the question. Commented Sep 30, 2013 at 13:15

3 Answers 3

4

Use the RegExp constructor instead of a RegExp literal. The constructor takes a string as its first param, so you can build it any way you like.

function remove_class(div, klass) {
    div.className = div.className.replace( new RegExp('(?:^|\\s)' + klass + '(?!\\S)'), '' );
}

Notice that no delimiters (the leading and trailing forward slashes) are needed when using the constructor.

Sign up to request clarification or add additional context in comments.

2 Comments

I have never used RegExp constructor. Do you have a working example?
Sorry, it was coming.
1

Instead using /regexp/ syntax you can use RegExp: something like this:

function remove_class(div, klass) {
    var regex = new RegExp('\/(?:^|\\s)' + klass + '(?!\\S)\/');
    div.className = div.className.replace( regex , '' );
}

1 Comment

Note, the RegExp delimiters (leading and trailing forward-slash) are only needed for a RegExp literal.
1

You can create the regexp like so:

var re = new RegExp("regex","g");

Check out https://stackoverflow.com/a/494046/1778812

3 Comments

If this question was a duplicate, you should have flagged it as such
@Phil rep not high enough to vote-to-close. (Copying answers between questions is still stupid.)
Is there a single answer in so-called duplicate with the syntax of the accepted answer to this question? new RegExp('(?:^|\\s)' + klass + '(?!\\S)'), '' No.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.