2017-08-06 143 views
0
export class Regex { 
    public static readonly BLANK = /^\s+$/; 
    public static readonly DIGITS = /^[0-9]*$/; 
} 

如何創建正則表達式類的擴展方法?我想用在需要Typescript正則表達式擴展方法

+2

如果你想在正則表達式通過'toString'方法,'RegExp'類中已經有一個名爲'source'的屬性。 –

回答

1

你可以這樣做Regex.Blank.toString():

interface RegExpConstructor { 
    readonly BLANK: RegExp; 
    readonly DIGITS: RegExp; 
} 

if (RegExp.BLANK === undefined) { 
    (RegExp as any).BLANK = /^\s+$/; 
} 

if (RegExp.DIGITS === undefined) { 
    (RegExp as any).DIGITS = /^[0-9]*$/; 
} 

code in playground

注意,有必要轉換爲any因爲你想要的新屬性爲readonly
此外,我使用RegExpConstructor而不是RegExp,因爲您希望道具是靜態的而不是實例。

由於@SayanPal評論,RegExp實例具有source屬性,它返回模式的字符串表示,如果你還想把它當作一個toString,那麼你可以這樣做:

RegExp.prototype.toString = function() { 
    return this.source; 
}