Reputation: 11116
Javascript String Match function
From the above documentation I see that the input to the String.prototype.match() function is "regexp". It's obviously not a string. What is its type?
In TypeScript how can I declare the input variable?
regex:regexp = ^\d{2}\/\d{2}\/\d{4}$
The above obviously throws an error as regexp is not a recognized type. How can I fix it?
Upvotes: 3
Views: 8573
Reputation:
You can look at the type information in 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.
Upvotes: 10
Reputation: 7621
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
Upvotes: 2