如何使用String.replace()来替换所有出现的模式

How to use String.replace() to replace ALL occurrences of a pattern

本文关键字:模式 替换 String 何使用 replace      更新时间:2023-09-26

在许多div中,我必须通过用句点替换空格来更改类名....

所以我试了这个

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

当类有两个单词时,它工作得很好…但是当类名有3个或更多单词时,它会失败....

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

有问题吗??

我使用Chrome 25, Win7, jQuery 1.8

编辑2

我需要替换空格来搜索所有具有特定类名的span元素。

我是这样使用jquery的

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

请求的结果应该是:

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

改为:

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

不要使用replace,使用splitjoin:

jqueryElements[index].className.split(' ').join('.');

.replace(/ /g, '.')代替。g表示全局(如"全局替换")。不过我对你想做的事有点怀疑。