1

I've a simple divwith various class attributs:

<div id="divId" class="anInformationIWantToGet aClassUsedForCss"></div>

I want to programatically get the anInformationIWantToGet class which vary, the problem should be easy because others classes are known, so a Regex like following should do the job:

var anInformationIWantToGet  = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/, '');

But it doesn't work and I don't understant why... What did I miss?

I create a Fiddle to test the problem.

PS : my browser is Firefox17.

5
  • 6
    Firefox 17 is ancient. You should upgrade ASAP. Commented May 5, 2015 at 11:51
  • Why not use classList? Commented May 5, 2015 at 11:52
  • @Quentin I completely agree, but it's not in my hands unfortunately... Commented May 5, 2015 at 11:53
  • @RGraham Because I thought I could to it with 1 line with Regex. If I found no good solution I'll loop over classList, sure. Commented May 5, 2015 at 11:55
  • One hint from me: never write a regex all parts of which are optional. Use anchors at least, e.g.: \s*(?:hover)?\s*$ Commented May 5, 2015 at 11:58

5 Answers 5

1

Try this Change you below code

var anInformationIWantToGet  = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/, '');

To

var anInformationIWantToGet  = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/g, '');

put g in regular expression.

And working updated fiddle

Ask for more, If above is not working/Understood.

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

Comments

0
/(\s*(aClassUsedForCss)?\s*)/
                       ^

You've made the class name you are looking for optional, so the first match will be the 0 or more white space at the beginning of the string.

Remove the ? and/or make it a global regex (by appending g).

Comments

0

This will work

FiddleChanged

function replaceClass(){
    /* Should not output 'hover' */
   var reqdClasName = div.className.match(/(\S*)\s*hover\s*/)[1];
   div.className.replace(reqdClasName, '');
   result.innerHTML = reqdClasName;   
}

Oops i had missed the replacing part. I ve updated

UpdatedFiddle

Comments

0

Be aware of replacing white spaces. Try this example.

var anInformationIWantToGet  = div.className.replace(/(\s*(?:aClassUsedForCss)\s*)/, ' ').trim();

Correct example.

Comments

0

We will also change it by just adding class which we required and remove the remaining like that way.

$("#myDiv").attr("class","aClassUsedForCss");

FIDDLE DEMO

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.