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');
jahroy
  • 22,322
  • 9
  • 59
  • 108
andrescabana86
  • 1,778
  • 8
  • 30
  • 56
  • err, why are you doing this? spaces separate class names; combining them doesn't make any sense. – Eevee Feb 28 '13 at 01:43

2 Answers2

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • global means all chars??? including '-' or '_'?? because i want to replace only spaces, white spaces... – andrescabana86 Feb 28 '13 at 01:54
  • Global means "_perform this substitution multiple times on each piece of input_". – jahroy Feb 28 '13 at 01:55
  • 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... – andrescabana86 Feb 28 '13 at 01:58
  • 1
    No need to remove the question. I recommend doing some reading on JavaScript regex, though. Here's [a good place to start](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp) – jahroy Feb 28 '13 at 02:04
  • i make a new test case, see the jsperf.com/split-vs-replace/2 and give me an opinion of this... thank you – – andrescabana86 Feb 28 '13 at 02:14
3

Don't use replace, use split and join:

jqueryElements[index].className.split(' ').join('.');
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i agree with this... in this http://jsperf.com/split-vs-replace test case the split().join() function has the best performance in all browsers thank you for the answer – andrescabana86 Feb 28 '13 at 02:09
  • i make a new test case, see the http://jsperf.com/split-vs-replace/2 and give me an opinion of this... thank you – andrescabana86 Feb 28 '13 at 02:13