-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})$/.

1
  • 2
    The first result of "javascript string to regex"... Commented Jan 13, 2020 at 11:57

2 Answers 2

2

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})$/
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this and doesn't work. Check the following fiddle: jsfiddle.net/MavrosGatos/p96txL7d/3
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.
"Also, you must escape the backslashes" - That's not the only character you have to escape.
@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
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.

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.