我想将字符串中的空格转换为另一个字符。
例如: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]="-";}
}
答案 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(" ", "-");