213

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.

thednp
  • 4,401
  • 4
  • 33
  • 45
  • 5
    The biggest question I have, right now, is why are you making a jQuery object from a string, instead of `"some+multi+word+string".replace(/\+/g,' ');`? Oh, and take a read of [Mozilla Developer Network's 'Regular Expressions'](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) page. It's helpful, and explains things pretty well. – David Thomas Nov 26 '12 at 23:33
  • actually it's a variable that turns into a string – thednp Nov 26 '12 at 23:34
  • But if the variable has the value of a string, or a string is assigned to that variable, just call `replace()` on the variable: `var str = 'some+multi+word+string'; str.replace(/\+/g,' ');` – David Thomas Nov 26 '12 at 23:35
  • 2
    @DavidThomas: That won't do anything at all. You have to use the result from the `replace` method, it doesn't change the string that it's called on. E.g. `str = str.replace(/\+/g, ' ');` – Guffa Nov 26 '12 at 23:42
  • @Guffa: I know, for reasons that made sense at the time, I opted to leave out the assignation to another variable. I think I was just trying to show how to use `replace()` on a variable. And, apparently, leaving out the essential part about doing something useful... =/ – David Thomas Nov 26 '12 at 23:44
  • I vote for regular expression solution – Say Truth Aug 28 '17 at 09:27
  • A modern solution to this problem would be `str.replaceAll()`. You can use it like `'some+multi+word+string'.replaceAll('+', ' ' );` – AbsarAkram Jul 03 '23 at 08:30

3 Answers3

434

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

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • how can I use a variable in this code like this example: for (i = 0; i <= 100; i++) { str = str.replace(/"_0x69b9[" + i.toString() + "]"/g, _array[i]); } – SalmanShariati Jan 15 '15 at 10:11
  • 1
    You would create a `RegExp` object from a string: `str = str.replace(new RegExp('"_0x69b9[' + i + ']"', 'g'), _array[i]);`. However, consider if you instead can use `(\d+)` in the pattern to match any number and catch it for lookup in a replacement function, that way you could replace all instances in one replacement instead of doing 101 replacements. – Guffa Jan 15 '15 at 11:16
  • 1
    In case you can't get it to work, it's easy to overlook that /\+/g is not inside quotes. It took a bit of head scratching before I realised that. – Stack Man Oct 22 '15 at 17:29
  • 2
    can we pass a variable instead of fixed string? – Jitendra Pancholi Sep 20 '19 at 07:07
  • It works with characters but how can we remove multiple blank spaces from a string eg. '999 999 9999'.replace(/\ /g, ' '); does not work. kindly share any suggestion. Thanks. – Kamlesh Nov 25 '19 at 14:40
50
'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • Yes, it needs to be regex, and yes the `g` switch is required. But, no: [`Uncaught TypeError: Object [object Object] has no method 'replace'`](http://jsfiddle.net/davidThomas/eD23g/). – David Thomas Nov 26 '12 at 23:37
  • @DavidThomas I've been thinking about this for 4 years, and I disagree. Or rather, I can't reproduce your error. – Madbreaks Aug 18 '16 at 17:38
  • 3
    it's haunted madbreaks deeply. Sleep has not come easy the last 4 years whilst @Madbreaks mind is going crazy with ideas on how it doesn't work - on another note ^+1 - thanks for explaining the g in the replace() function –  Jan 05 '17 at 11:44
  • Downvoter, please explain – Madbreaks Jul 28 '17 at 18:10
  • @Madbreaks David posted that before you edited your answer. Before it used the Jquery syntax. "$(string).replace..". This will result in an error. You can check the history of your answer and also click the link of the error David had shown. – Kerwin Sneijders Oct 15 '19 at 11:54
  • 1
    Ah, thanks for the reminder @KerwinSneijders – Madbreaks Oct 16 '19 at 17:57
10

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.

phyatt
  • 18,472
  • 5
  • 61
  • 80