【问题标题】:why does str.replace() only replace the first found item?为什么 str.replace() 只替换第一个找到的项目?
【发布时间】:2014-10-22 05:50:00
【问题描述】:
text = "1/2/3"
result = text.replace("/", "");

我希望结果是“123”,但结果却是“12/3” 为什么?

【问题讨论】:

标签: javascript replace


【解决方案1】:

添加全局选择“g”标志并在第一个参数中使用正则表达式而不是字符串。

result = text.replace(/\//g, "");

【讨论】:

  • @AdrianoRepetti 是的,是的,正要在答案中指出这一点。谢谢
  • @AdrianoRepetti “正则表达式参数”是什么意思?
  • @zerkms 措辞不佳但“第一个参数(模式)是正则表达式”.
【解决方案2】:

您可以使用正则表达式作为参数来替换全局选择。

"1/2/3".replace(/\//g, "")

【讨论】:

    【解决方案3】:

    你可以试试下面的正则表达式

    "1/2/3".replace(/\//g,"");
    

    这会将所有/ 元素替换为""

    【讨论】:

    • 与 Ahmad、Vishwanath 和 Felipe 的答案相比,这有什么不同/更好?
    【解决方案4】:

    另一种方法:

    String.prototype.replaceAll = function(matchStr, replaceStr) {
      return this.replace(new RegExp(matchStr, 'g'), replaceStr);
     };
    var str = "1/2/3";
    result = str.replaceAll('/', '');
    

    【讨论】:

      【解决方案5】:
      a = "1/2/3"
      a =a.split("/").join("")
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      相关资源
      最近更新 更多