【问题标题】:how to replace all instances of a sub string in a string如何替换字符串中子字符串的所有实例
【发布时间】:2013-03-18 17:40:11
【问题描述】:

我正在尝试使用 RegEx 将大字符串拆分为较小的部分,作为其中的一部分,我正在尝试替换这个较大字符串中子字符串的所有实例。我一直在尝试使用替换功能,但这只会替换子字符串的第一个实例。如何替换较大字符串中子字符串的所有实例?

谢谢

斯蒂芬

【问题讨论】:

    标签: regex actionscript-3


    【解决方案1】:

    'g' 添加到 searchExp。例如/i_want_to_be_replaced/g

    【讨论】:

    • 别忘了,正则表达式不在“”之内。 (我犯了那个错误)
    【解决方案2】:

    一种快速的方法是使用拆分和连接:

    function quickReplace(source:String, oldString:String, newString:String):String
    {
        return source.split(oldString).join(newString);
    }
    

    【讨论】:

      【解决方案3】:

      除了@Alex 的回答,您可能还会发现this answer 很方便, 使用 String 的replace() 方法。

      这是一个sn-p:

      function addLinks(pattern:RegExp,text:String):String{
          var result = '';
          while(pattern.test(text)) result = text.replace(pattern, "<font color=\"#0000dd\"><a href=\"$&\">$&</a></font>");
          if(result == '') result+= text;//if there was nothing to replace
          return result;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-29
        • 1970-01-01
        • 2021-08-16
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        • 2012-11-14
        相关资源
        最近更新 更多