1

I want to convert the space in a string into another character.

Ex:
var country = "United States"

I want the space to be "-" so:
var country = "Unites-States"

This is what I tried:

var country ="United States";
var countryArray = country.split(" ");
var newCountry = function(){
for(i=0;i<countryArray.length;i++){
    if(countryArray[i]===","){
    return countryArray[i]="-";}
}
1
  • 1
    and what about simple RegEx : country = country.replace(" ","-") Commented Sep 1, 2013 at 4:36

3 Answers 3

2

Using the string.replace function :

var country = "United States";
//var newCountry = country.replace(' ', '-'); //first space only
var newCountry = country.replace(/\s+/g, '-'); //this uses regexp if there is more than just 1 space / tab character.
Sign up to request clarification or add additional context in comments.

3 Comments

that only replace the first space, for example > United States of America will be United-States of America
Wow I was in the middle of answering when you answered it. :-)
Check the answer again.
1

Have you considered the string replace method?

Example:

newCountry = country.replace(" ", "-");

Comments

1

try this

country.replace(/ /g, ",");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.