How can I implement regular expressions (RegExp) in TypeScript?
For example:
var regex = new RegExp('^[1-9]\d{0,2}$', trigger); // I encounter an exception in the Chrome console
How should I correctly use TypeScript regex in this case?
How can I implement regular expressions (RegExp) in TypeScript?
For example:
var regex = new RegExp('^[1-9]\d{0,2}$', trigger); // I encounter an exception in the Chrome console
How should I correctly use TypeScript regex in this case?
The new RegExp constructor accepts two arguments: the pattern and the flags. Ensure the second argument is a valid flag (e.g., ‘g’, ‘i’, ‘m’).
In your example, it seems like trigger is intended to be part of the pattern, which is incorrect.
var trigger = "2"; // This should be part of the pattern, not the flags
var regex = new RegExp('^[1-9]\\d{0,2}$'); // Corrected usage without flags
console.log(regex.test(trigger)); // Use the test method to check the match
If the trigger variable is meant to be part of the pattern, concatenate it directly into the pattern string.
var trigger = "2";
var regexPattern = `^[1-9]\\d{0,${trigger}}$`; // Embed trigger in the pattern
var regex = new RegExp(regexPattern);
console.log(regex.test("25")); // Test with a sample string