0

I have a regular expression that works when constructed via the native regex primitive:

var regex = /^(?:533-)?\d{3}-\d{4}$/;
'533-123-4567'.match(regex)
["533-123-4567", index: 0, input: "533-123-4567"]

but fails when it is constructed via a string:

var regex = new RegExp('/^(?:533-)?\d{3}-\d{4}$/');
'533-123-4567'.match(regex)
null

I have tried escaping the back slashes to no avail. Where is documentation on what characters must be escaped?

John Hoffman
  • 17,857
  • 20
  • 58
  • 81

4 Answers4

1

You would have to do this in your 2nd example

var regex = new RegExp('^(?:533-)?\\d{3}-\\d{4}$');

console.log('533-123-4567'.match(regex));

here you don't need to specify /regex/ just regex would do
also changing \d to \\d worked for me

This is given in the MDN docs. you can check it out

marvel308
  • 10,288
  • 1
  • 21
  • 32
1

You need to escape \. Check out the regex generated from same regex expression. In the below output, you will notice that in the string \d got changed to d.

var regex = /^(?:533-)?\d{3}-\d{4}$/;
console.log(regex);

var str = '/^(?:533-)?\d{3}-\d{4}$/';
console.log(str)

Just escape \d and your regex will work.

var regex = /^(?:533-)?\d{3}-\d{4}$/;
console.log('533-123-4567'.match(regex));

var regex = new RegExp('^(?:533-)?\\d{3}-\\d{4}$');
console.log('533-123-4567'.match(regex));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

You need to:

  • Escape your \ signs as \\ .
  • Remove your enclosing / signs.

var regex = new RegExp('^(?:533-)?\\d{3}-\\d{4}$');
console.log('533-123-4567'.match(regex));
Sebas
  • 21,192
  • 9
  • 55
  • 109
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
1

When you use the constructed new RegExp () you do not need to escape or enclosing (//) the string. Your second regex may looks like this:

var regex = new RegExp('^(?:533-)?\\d{3}-\\d{4}$');
console.log('533-123-4567'.match(regex));

Refer to the documentation here.

However, the first regex need yo be escape because you are not calling the constructor and you have to precise to the javascript that you are writing is some regex.

SphynxTech
  • 1,799
  • 2
  • 18
  • 38