JavaScript .replace only replaces first Match

Yardstermister picture Yardstermister · Jul 9, 2010 · Viewed 111.1k times · Source
var textTitle = "this is a test"
var result = textTitle.replace(' ', '%20');

But the replace functions stops at the first instance of the " " and I get the

Result : "this%20is a test"

Any ideas on where Im going wrong im sure its a simple fix.

Answer

Nick Craver picture Nick Craver · Jul 9, 2010

You need a /g on there, like this:

var textTitle = "this is a test";
var result = textTitle.replace(/ /g, '%20');

console.log(result);

You can play with it here, the default .replace() behavior is to replace only the first match, the /g modifier (global) tells it to replace all occurrences.