3

In many divs I have to change the class name by replacing spaces with periods....

So I tried this

$(jqueryElements).each(function(index)
{ 
    jqueryElements[index].className.replace(' ','.');
});

When the class has two words it works fine... But when the class name has 3 or more words it fails....

className='one word';
jqueryElement[index].className.replace(' ','.'); // console-> one.word
className='many many words';
jqueryElement[index].className.replace(' ','.'); // console-> many.many words

There is something wrong??

I'm using Chrome 25, Win7, jQuery 1.8

EDIT 2

I need to replace spaces to search all the span elements that have a particular class name.

So I use jquery in this way...

$('#span-container').find('span.'+jqueryElements[index].className.replace(' ','.').text('there are '+span_counter+'spans with this classname');

The result of this request shoud be:

 $('#span-container').find('span.many.many.words).text('there are '+span_counter+'spans with this classname');

Instead I have:

$('#span-container').find('span.many.many words).text('there are '+span_counter+'spans with this classname');
1
  • err, why are you doing this? spaces separate class names; combining them doesn't make any sense. Commented Feb 28, 2013 at 1:43

2 Answers 2

3

Don't use replace, use split and join:

jqueryElements[index].className.split(' ').join('.');
Sign up to request clarification or add additional context in comments.

2 Comments

i agree with this... in this jsperf.com/split-vs-replace test case the split().join() function has the best performance in all browsers thank you for the answer
i make a new test case, see the jsperf.com/split-vs-replace/2 and give me an opinion of this... thank you
3

Use .replace(/ /g, '.') instead. The g means global (as in "global replace"). I am a bit skiptical about what you're trying to do though.

5 Comments

global means all chars??? including '-' or '_'?? because i want to replace only spaces, white spaces...
Global means "perform this substitution multiple times on each piece of input".
great! this works fine! thank you, im not sure if i have to erase the question... because is simple question, but in all tutorials the answer is ".replace(' ','.'), this is a different aproach...
No need to remove the question. I recommend doing some reading on JavaScript regex, though. Here's a good place to start
i make a new test case, see the jsperf.com/split-vs-replace/2 and give me an opinion of this... thank you –

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.