jQuery - replace all instances of a character in a string

thednp picture thednp · Nov 27, 2012 · Viewed 489.8k times · Source

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.

Answer

Guffa picture Guffa · Nov 27, 2012

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