【问题标题】:How to change a character of an string into a different character?如何将字符串的字符更改为不同的字符?
【发布时间】:2013-09-04 12:03:54
【问题描述】:

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

例如:
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]="-";}
}

【问题讨论】:

  • 那么简单的正则表达式呢:country = country.replace(" ","-")

标签: javascript arrays character converter


【解决方案1】:

使用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.

【讨论】:

  • 只替换第一个空格,例如 > United States of America 将是 United-States of America
  • 哇,你回答的时候我正在回答。 :-)
  • 再次检查答案。
【解决方案2】:

你考虑过字符串替换方法吗?

例子:

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

【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 2014-12-27
      • 2018-06-07
      • 2018-02-12
      相关资源
      最近更新 更多