-1

I have a regex when I instantiate the Regex object like this:

this.checkRegex = new RegExp(/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/);

It works fine, however If I store the regex in string it does not work:

  private checkReg: string = '/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/';
  this.checkRegex = new RegExp(this.checkReg);

I am using angular-typescript. What is the thing I am missing here when I am trying to instantiate by throwing string inside the constructor. Code sample will be really appreciated. Thanks for your help.

1

2 Answers 2

1

When you are passing a string to the RegExp constructor, you need to change it a little bit. Instead of

'/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/'

You would omit the preceding and trailing slash

'^([0|\\[+][0-9]{0,5})?([1-9][0-9]{0,15})$'

Note also double escaping the back slash.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked however I did not have to add double back slash. Thanks for your help.
1

If you want to store the RegExp as a String, store it without the forward slashes at the front and back. When creating the RegExp object, those get escaped:

new RegExp('/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/');

will result in

/\/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$\//

while,

new RegExp('^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$');

will work:

/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.