[TypeScript] 實現字串全部替換

當進行string.replace() 時, 若遇到多個字串須要replace 時, 因為JavaScript 預設只會執行第一個遇到的charset, 所以之後的不會進行. 若要令它全部取代, 則須要利用regular expression.

export class StringUtil {
    public static replaceAll(value: string, originalValue: string, replaceValue: string, isCaseSensitive = false): string {
        let result = value;
        let regularExpressionFlag = 'g';
        regularExpressionFlag += isCaseSensitive ? 'i' : '';
        result = result.replace(new RegExp(originalValue, regularExpressionFlag), replaceValue);
        return result;
    }
}

其中於設定RegExp 時, ‘g’ 是指Global, 若要設為case insensitive, 則可以改為’gi’, 其中的’i’ 就是’insensitive’ 的意思.

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.