-1

I need to pass a regular expression in a validation function in my code that can only be set by an administrator in a back office platform as a string (e.g. '/^(?:\d{8}|\d{11})$/'). After it is passed I need to take this string and transform it into an actual javascript regex in order to use it.

const validator = (regex, value) => {
  if (value && regex.test(value)) {
    return 'Yeah!!';
  }
  return null;
};

So I need this '/^(?:\d{8}|\d{11})$/' to be like this /^(?:\d{8}|\d{11})$/.

MavrosGatos
  • 507
  • 2
  • 6
  • 19

2 Answers2

1

You can initialize a regex with the RegExp method (documentation on MDN):

The RegExp constructor creates a regular expression object for matching text with a pattern.

const regex2 = new RegExp('^(?:\\d{8}|\\d{11})$');
console.log(regex2); // /^(?:\d{8}|\d{11})$/
Ismael Padilla
  • 4,666
  • 4
  • 23
  • 33
  • I tried this and doesn't work. Check the following fiddle: https://jsfiddle.net/MavrosGatos/p96txL7d/3/ – MavrosGatos Jan 13 '20 at 12:10
  • Sorry, I made a mistake and I've edited my answer. When using RegExp, you don't include the forward slashes in the string. Also, you must escape the backslashes. Try it now. – Ismael Padilla Jan 13 '20 at 12:17
  • _"Also, you must escape the backslashes"_ - That's not the only character you have to escape. – Andreas Jan 13 '20 at 13:24
0

You could instantiate the RegExp class and use it in two ways:

First:

new RegExp('<expression>').test(...)

Second:

/<expression>/.test(...)

Both ways will create an RegExp instance.

When to use one over the other?

Using the new RegExp way you can pass variables to the expression, like that:

new RegExp('^abc' + myVar + '123$');

Which you can't do using the second way.

Felipe Malara
  • 1,601
  • 1
  • 5
  • 13