jQuery - replace all instances of a character in a string

JqueryStringReplace

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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.)

Solution 2 - Jquery

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthednpView Question on Stackoverflow
Solution 1 - JqueryGuffaView Answer on Stackoverflow
Solution 2 - JqueryMadbreaksView Answer on Stackoverflow
Solution 3 - JqueryphyattView Answer on Stackoverflow