简体   繁体   English

match()函数输入的TypeScript“类型”是什么

[英]What's the TypeScript “type” of the input to the match() function

Javascript String Match function Javascript字符串匹配功能

From the above documentation I see that the input to the String.prototype.match() function is "regexp". 从上面的文档中,我看到String.prototype.match()函数的输入是“ regexp”。 It's obviously not a string. 显然不是字符串。 What is its type? 它是什么类型?

In TypeScript how can I declare the input variable? 在TypeScript中,如何声明输入变量?

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

The above obviously throws an error as regexp is not a recognized type. 上面显然会引发错误,因为regexp不是可识别的类型。 How can I fix it? 我该如何解决?

You can look at the type information in lib.d.ts : 您可以在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;

You can see that the type for a regular expression is RegExp , and there are two definitions for match , one taking a string, the other a RegExp. 您可以看到正则表达式的类型为RegExp ,并且match有两个定义,一个定义为字符串,另一个为RegExp。

Try this 尝试这个

//inside the class
//this expression is to test valid email

public reg: RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

and then you can test it in your class 然后你可以在课堂上测试它

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

//out side the class //课堂外

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM