Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

expression stored in variable as string

I have this code that works.

myDate = str.match(/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g);

However I would like to store the expression as a variable and use that instead.
Something like this:

pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g"; // I understand this is wrong somehow

myDate = str.match(pattern);

How do I store my expression as a variable and use it the way I have shown?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

As with most things in JavaScript, a Regular Expression pattern is an object – specifically, a RegExp object. As explained in MDN:

There are two ways to create a RegExp object: a literal notation and a constructor.

  • The literal notation’s parameters are enclosed between slashes and do not use quotation marks.
  • The constructor function’s parameters are not enclosed between slashes but do use quotation marks.

The additional point relevant to your example is that the g flag is added on the end of the literal notation, but as a separate parameter in the constructor function. So either of the following will work:

pattern = /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
pattern = new RegExp('\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})', 'g');

The reason your attempt didn’t give an error, but didn’t match the string is explained on the MDN page for the match function:

If regexp is a non-RegExp object, it is implicitly converted to a RegExp by using new RegExp(regexp).

So your code was equivalent to this:

pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g";
myDate = str.match(new RegExp(pattern));

When what you wanted was this:

pattern = "(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})";
myDate = str.match(new RegExp(pattern, "g"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading