RegExp in TypeScript

JavascriptRegexTypescript

Javascript Problem Overview


How can I implement Regexp in TypeScript?

My Example:

var trigger = "2"
var regex = new RegExp('^[1-9]\d{0,2}$', trigger); // where I have exception in Chrome console

Javascript Solutions


Solution 1 - Javascript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Solution 2 - Javascript

You can do just:

var regex = /^[1-9]\d{0,2}$/g
regex.test('2') // outputs true

Solution 3 - Javascript

In typescript, the declaration is something like this:

const regex : RegExp = /.+\*.+/;

using RegExp constructor:

const regex = new RegExp('.+\\*.+');

Solution 4 - Javascript

const regex = /myRegexp/

console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!

The Regex literal notation is commonly used to create new instances of RegExp

     regex needs no additional escaping
      v
/    regex   /   gm
^            ^   ^
start      end   optional modifiers

As others sugguested, you can also use the new RegExp('myRegex') constructor.
But you will have to be especially careful with escaping:

regex: 12\d45
matches: 12345
                           Extra excape because it is part of a string
                            v
const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzrabzdnView Question on Stackoverflow
Solution 1 - JavascriptNiccolò CampolungoView Answer on Stackoverflow
Solution 2 - Javascriptsebas2dayView Answer on Stackoverflow
Solution 3 - JavascriptNavin AdheView Answer on Stackoverflow
Solution 4 - JavascriptAriView Answer on Stackoverflow