1

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

前任:
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]="-";}
}
4

3 回答 3

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.
于 2013-09-01T04:36:11.217 回答
1

试试这个

country.replace(/ /g, ",");
于 2013-09-01T04:37:03.097 回答
1

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

例子:

newCountry = country.replace(" ", "-");
于 2013-09-01T04:38:33.827 回答