user2736657
user2736657

Reputation: 13

How to change a character of an string into a different character?

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

Answers (3)

OneOfOne
OneOfOne

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

Milad Hosseinpanahi
Milad Hosseinpanahi

Reputation: 1495

try this

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

Upvotes: 1

FernandoZ
FernandoZ

Reputation: 438

Have you considered the string replace method?

Example:

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

Upvotes: 1

Related Questions