-1

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?

1
  • 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. Commented Jan 31 at 6:40

2 Answers 2

7
var str = 'new zealand';
str = str.replace(/\s+/g, '_');
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for fastest option according to these jsperf benchmarks - jsperf.com/split-join-vs-replace/2
1

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

If you can be certain that there is always only one space.
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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.