views:

161

answers:

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

+7  A: 

You need a /g on there, like this:

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

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.

Nick Craver
Did exactly what was needed. Thank you.
Yardstermister
A: 

Try using replaceWith() or replaceAll()

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

a.feng
...who upvoted this?
Nick Craver
Didn't he ask for a JQuery version? I don't see a .replace() in the JQuery API - that's vanilla Javascript.
a.feng
@Nick Are you jealous or what? :)
Nikita Rybak
@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
@Nick: Fair enough I guess; I'm just trying to give him what he asked for.
a.feng
@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
+1  A: 
textTitle.replace(/ /g, '%20');
Nikita Rybak
A: 

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-
+1  A: 

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

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

32bitkid