Typescript正则表达式扩展方法

时间:2017-08-06 05:16:10

标签: javascript regex typescript

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

如何为Regex Class创建扩展方法?我想在需要的地方使用Regex.Blank.toString()

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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,那么您可以这样做:< / p>

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