Reputation: 13
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]="-";}
}
Upvotes: 1
Views: 60
Reputation: 99274
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.
Upvotes: 2
Reputation: 438
Have you considered the string replace method?
Example:
newCountry = country.replace(" ", "-");
Upvotes: 1