【问题标题】:Typescript Regex Extension methods打字稿正则表达式扩展方法
【发布时间】:2017-08-06 05:16:09
【问题描述】:
export class Regex { 
    public static readonly BLANK = /^\s+$/;
    public static readonly DIGITS = /^[0-9]*$/;
}

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

【问题讨论】:

  • 如果你想要toString方法的正则表达式,那么RegExp类中已经有一个属性叫做source

标签: javascript regex typescript


【解决方案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,那么您可以这样做:

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

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 2019-04-17
    • 2019-04-25
    • 1970-01-01
    • 2016-09-26
    • 2019-06-27
    • 2020-07-07
    • 2019-02-17
    • 2018-01-21
    相关资源
    最近更新 更多