-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
  • 529
  • 2
  • 6
  • 20

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
  • 5,246
  • 4
  • 23
  • 35
  • 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
  • @Andreas yes it is, backslashes are the only characters with special meaning in strings in js (we are not talking about escaping the regex tokens here, just the string so that it's a valid string) Technically you'd also need to escape your string delimiters if any within the string but that's common sense Also If that string is coming from an input then it's already escaped – Tofandel Mar 03 '23 at 10:36
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,796
  • 1
  • 7
  • 13