jQuery - replace all instances of a character in a

2019-01-07 04:19发布

This question already has an answer here:

This does not work and I need it badly

$('some+multi+word+string').replace('+', ' ' );

always gets

some multi+word+string

it's always replacing for the first instance only, but I need it to work for all + symbols.

3条回答
女痞
2楼-- · 2019-01-07 05:01

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-07 05:19
'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

查看更多
孤傲高冷的网名
4楼-- · 2019-01-07 05:22

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

查看更多
登录 后发表回答