views:

59

answers:

2

I would like to modify my strings so i can replace the character ' ' with '_' using JS,for example "new zeland"=>"new_zeland" how can i do that?

+7  A: 
var str = 'new zealand';
str = str.replace(/\s+/g, '_');
Rob
+1  A: 

You could use Rob's code, but it uses a regular expression to find the space, while it would be faster to just search for a literal space:

var string = 'new zealand';
var newString = string.replace(' ', '_');
Douwe Maan
If you can be certain that there is always only **one** space.
Felix Kling
Well, in `new zealand`, there is ;) And we don't know what the OP wants. He might want to replace every space by an underscore, so `new[3 spaces]zealand` would be `new___zealand`...
Douwe Maan