繁体   English   中英

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

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

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

也许有一些方法可以通过使用自定义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;
}

为了向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);}

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

 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);
}

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

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

或者我只是这样做:

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

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

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

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

就我而言,我使用的是 Node 12+。 并且 Node 没有.replaceAll() (检查MDN 上浏览器兼容性)。

但我的解决方案是使用 Regex(/g) 和.replace() 关键是使用/g

const s = `[People,Contracts,Facilities]`;
// My case was to remove the `[` and `]`
// So the key is using `/g`
const res = s.replace(/\[/g, '').replace(/\]/g, '');

暂无
暂无

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

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