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

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
Yardstermister
  • 1,861
  • 3
  • 14
  • 12

7 Answers7

273

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.

Jonathan
  • 2,225
  • 4
  • 20
  • 37
Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
9
textTitle.replace(/ /g, '%20');
Nikita Rybak
  • 66,340
  • 22
  • 154
  • 177
4

Try using a regex instead of a string for the first argument.

"this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"

J. Holmes
  • 18,226
  • 5
  • 44
  • 51
3

From w3schools

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Would be better to use a regex here then:

textTitle.replace(/ /g, '%20');
Jhonny D. Cano -Leftware-
  • 17,104
  • 14
  • 80
  • 102
3

For that you neet to use the g flag of regex.... Like this :

var new_string=old_string.replace( / (regex) /g,  replacement_text);

That sh

Subham Debnath
  • 609
  • 6
  • 8
3

The same, if you need "generic" regex from string :

const textTitle = "this is a test";
const regEx = new RegExp(' ', "g");
const result = textTitle.replace(regEx , '%20');
console.log(result); // "this%20is%20a%20test" will be a result
    
Nigrimmist
  • 7,468
  • 4
  • 42
  • 45
-7

Try using replaceWith() or replaceAll()

http://api.jquery.com/replaceAll/

amfeng
  • 1,045
  • 5
  • 17
  • 1
    Didn't he ask for a JQuery version? I don't see a .replace() in the JQuery API - that's vanilla Javascript. – amfeng Jul 09 '10 at 17:05
  • 2
    @Nick Are you jealous or what? :) – Nikita Rybak Jul 09 '10 at 17:05
  • 4
    @Nikita - No...this isn't at all relevant to the question. the OP is mistaken including jQuery in there at all, this is vanilla JavaScript, having *nothing* to do with jQuery or it's replace methods... – Nick Craver Jul 09 '10 at 17:06
  • @Nick: Fair enough I guess; I'm just trying to give him what he asked for. – amfeng Jul 09 '10 at 17:09
  • 2
    @afeng - I understand that, try and read the entire question though, not the title only...the question is about the `.replace()` string operator, no jQuery involved, it's a common mix-up, unfortunately. – Nick Craver Jul 09 '10 at 17:11