Fractaliste
Fractaliste

Reputation: 5957

How to replace a className part with JavaScript Regex?

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.

Upvotes: 1

Views: 713

Answers (5)

Lakhan
Lakhan

Reputation: 13216

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

Upvotes: 0

andale
andale

Reputation: 473

Be aware of replacing white spaces. Try this example.

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

Correct example.

Upvotes: 0

wallop
wallop

Reputation: 2571

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

Upvotes: 0

Quentin
Quentin

Reputation: 943480

/(\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).

Upvotes: 0

saikiran.vsk
saikiran.vsk

Reputation: 1796

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.

Upvotes: 1

Related Questions