Javascript String.Replace 仅替换匹配字符串的第一次出现。如何替换*所有*出现?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37197311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:01:36  来源:igfitidea点击:

String.Replace only replaces first occurrence of matched string. How to replace *all* occurrences?

javascriptregextypescript

提问by James W Simms

Coming from other programming languages, String.replace()typically replaces all occurrences of matching strings. However, that is not the case with javascript/typescript. I found a number of solutions on the web with javascriptutilizing regex. I immediately had issues with this solution because of special characters. I suspect there is a way to correct this with regex, but I am not a regex expert. As many have done before me, I created my own method.

来自其他编程语言,String.replace()通常替换所有匹配字符串。但是,javascript/typescript并非如此。我在网上找到了许多使用正则表达式的javascript解决方案。由于特殊字符,我立即遇到了此解决方案的问题。我怀疑有一种方法可以用正则表达式来纠正这个问题,但我不是正则表达式专家。正如许多人在我之前所做的那样,我创建了自己的方法。

Perhaps there are ways to improve performance by making use of a custom StringBuilder()class. I welcome any thoughts.

也许有一些方法可以通过使用自定义StringBuilder()类来提高性能。我欢迎任何想法。

public static Replace = function (originalString: string, oldValue: string, newValue: string, ignoreCase: boolean = false) {
    //
    // if invalid data, return the original string
    //
    if ((originalString == null) || (oldValue == null) || (newValue == null) || (oldValue.length == 0) )
        return (originalString);
    //
    // do text replacement
    //
    var dest = "";        
    var source: string = originalString;
    if (ignoreCase) 
    {
        source = source.toLocaleLowerCase();
        oldValue = oldValue.toLowerCase();
    }
    //
    // find first match
    //
    var StartPos = 0;
    var EndPos = source.indexOf(oldValue, StartPos);
    var Skip = (EndPos >= 0) ? EndPos - StartPos : source.length-StartPos;   
    //
    // while we found a matched string
    //     
    while (EndPos > -1) {
        //
        // copy original string skipped segment
        //
        if (Skip > 0) dest += originalString.substr(StartPos, Skip);            
        //
        // copy new value
        //
        dest += newValue;
        //
        // skip over old value
        //
        StartPos = EndPos + oldValue.length;
        //
        // find next match
        //
        EndPos = source.indexOf(oldValue, StartPos);
        Skip = (EndPos >= 0) ? EndPos - StartPos : source.length - StartPos;    
    }
    //
    // append the last skipped string segment from original string
    //
    if (Skip > 0) dest += originalString.substr(StartPos, Skip);   

    return dest;
}

In order to add support to this method to the stringclass I added the following code:

为了向类添加对此方法的支持,string我添加了以下代码:

interface String { EZReplace(oldValue: string, newValue: string, ignorCase?: boolean): string; }

String.prototype.EZReplace = function (oldValue: string, newValue: string, ignorCase: boolean = false) {
return EZUtil.Replace(this, oldValue, newValue, ignorCase);}

....After re-viewing other posts, I modified the code to use regular expressions. It would be interesting to execute performance tests.

....重新查看其他帖子后,我修改了代码以使用正则表达式。执行性能测试会很有趣。

 public static Replace = function (originalString: string, oldValue: string, newValue: string, ignoreCase: boolean = false) {
    //
    // if invalid data, return the original string
    //
    if ((originalString == null) || (oldValue == null) || (newValue == null) || (oldValue.length == 0))
        return (originalString);
    //
    // set search/replace flags
    //
    var Flags: string = (ignoreCase) ? "gi" : "g";
    //
    // apply regex escape sequence on pattern (oldValue)
    //
    var pattern = oldValue.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\^$\|]/g, "\$&");
    //
    // replace oldValue with newValue
    //
    var str = originalString.replace(new RegExp(pattern, Flags), newValue);
    return (str);
}

回答by basarat

In typescript, String.Replace only replaces first occurrence of matched string. Need String.replaceAll() method

在打字稿中, String.Replace 只替换匹配字符串的第一次出现。需要 String.replaceAll() 方法

There is nothing special to TypeScript here (after all TypeScript is just JavaScript with type annotations). JavaScript string.replaceonly replaces the first instance if given a string. Only way to get replace all is to use a regexwith /gmodifier.

TypeScript 在这里没有什么特别之处(毕竟 TypeScript 只是带有类型注释的 JavaScript)。string.replace如果给定字符串,JavaScript只会替换第一个实例。获得全部替换的唯一方法是使用regexwith/g修饰符。

Alternatively I just do:

或者我只是这样做:

somestring.split('oldString').join('newString');

回答by Ziggler

In my case I did like this in TypeScript.

就我而言,我在 TypeScript 中确实喜欢这样做。

this.mystr= this.mystr.replace(new RegExp('class="dec-table"', 'g'), 'class="copydec-table"');

Credits to How to replace all occurrences of a string in JavaScript?

归功于如何替换 JavaScript 中所有出现的字符串?