简体   繁体   English

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

[英]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]="-";}
}

Using the string.replace function : 使用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.

尝试这个

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

Have you considered the string replace method? 你考虑过字符串替换方法吗?

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM