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?
-
This question is similar to: How do I replace all occurrences of a string?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2025-01-31 06:40:11 +00:00Commented Jan 31 at 6:40
Add a comment
|
2 Answers
var str = 'new zealand';
str = str.replace(/\s+/g, '_');
1 Comment
widged
+1 for fastest option according to these jsperf benchmarks - jsperf.com/split-join-vs-replace/2
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(' ', '_');
2 Comments
Felix Kling
If you can be certain that there is always only one space.
Douwe Maan
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...