【问题标题】:What's the TypeScript "type" of the input to the match() functionmatch() 函数输入的 TypeScript“类型”是什么
【发布时间】:2016-11-22 16:21:05
【问题描述】:

Javascript String Match function

从上面的文档中,我看到 String.prototype.match() 函数的输入是“regexp”。这显然不是一个字符串。它的类型是什么?

在 TypeScript 中如何声明输入变量?

regex:regexp = ^\d{2}\/\d{2}\/\d{4}$

上面显然会引发错误,因为 regexp 不是可识别的类型。我该如何解决?

【问题讨论】:

  • var regex = /^\d{2}\/\d{2}\/\d{4}$/g regex.test(your variable) // 这将输出 true 和错误的结果
  • @Deep 那的类型定义是什么?我如何在 Typescript 中声明它?类似于 regex:regexp = ...
  • In the official declarations,参数可以是RegExpstring
  • 另外,请注意RegExp literals 用斜杠分隔(类似于字符串文字的引号)– /^\d{2}\/\d{2}\/\d{4}$/
  • 您不需要指定类型,因为值会提供该类型(只要将其括在斜杠中)。仅供参考,要匹配的参数类型将是 RegExp | string

标签: javascript regex string types typescript


【解决方案1】:

你可以查看lib.d.ts中的类型信息:

/**
  * Matches a string with a regular expression, and returns an array containing the results of that search.
  * @param regexp A variable name or string literal containing the regular expression pattern and flags.
  */
match(regexp: string): RegExpMatchArray;

/**
  * Matches a string with a regular expression, and returns an array containing the results of that search.
  * @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
  */
match(regexp: RegExp): RegExpMatchArray;

可以看到正则表达式的类型是RegExp,而match有两种定义,一种是字符串,一种是RegExp。

【讨论】:

    【解决方案2】:

    试试这个

    //inside the class
    //this expression is to test valid email
    
    public reg: RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    

    然后你可以在你的课堂上测试它

    this.reg.test("expression to test")
    

    //课外

    let reg = /^\d+$/;
    alert(reg.test("sd")); //will alert false
    

    【讨论】:

    • 警报(/^\d+$/.test("sd"));或者,您可以在不事先声明变量的情况下对其进行测试。
    猜你喜欢
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2019-04-04
    • 1970-01-01
    • 2012-10-24
    • 2019-06-07
    相关资源
    最近更新 更多