如何将字符串的字符更改为不同的字符?

时间:2013-09-01 04:33:10

标签: javascript arrays character converter

我想将字符串中的空格转换为另一个字符。

例如:var country = "United States"

我希望空间为“ - ”所以:
var country = "Unites-States"

这就是我的尝试:

var country ="United States";
var countryArray = country.split(" ");
var newCountry = function(){
for(i=0;i<countryArray.length;i++){
    if(countryArray[i]===","){
    return countryArray[i]="-";}
}

3 个答案:

答案 0 :(得分:2)

使用string.replace功能:

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.

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:1)

您是否考虑过字符串替换方法?

示例:

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