1

A short question: The following line throws SyntaxError: nothing to repeat

var regexTel = new RegExp('\+[0-9 ]+');

Tools like http://www.regexpal.com/ says that the pattern works fine.

akop
  • 5,981
  • 6
  • 24
  • 51

5 Answers5

3

Remember that \ is special in string literals as well as in regular expressions, so a single \ in a string literal escapes what follows it at the string level; so your regex doesn't actually have that \ in it at all. (Since \+ is meaningless in a string literal, it's handled as simpley +.) You'd need to escape it at the string level with another backslash:

var regexTel = new RegExp('\\+[0-9 ]+');

But, in JavaScript, you don't have to use strings; use a regex literal instead, so you don't have that problem:

var regexTel = /\+[0-9 ]+/;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

If what you want is repeat a backslash \, you need to escape it:

var regexTel = new RegExp('\\+[0-9 ]+');
laurent
  • 88,262
  • 77
  • 290
  • 428
0

As others point out, it's either to add the slashes in the string you pass to the regex:

var regexTel = new RegExp('/\+[0-9 ]+/');

Or either use the more compact version that removes the use of the RegExp object:

var regexTel = /\+[0-9 ]+/;
Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93
-1

You have to escape "+" sign. In your regex "\" sign is recognized as a delimiter. Go with:

var regexTel = new RegExp(/\+[0-9 ]+/);
malutki5200
  • 1,092
  • 7
  • 15
-1

try this

var regexTel = new RegExp(/\+[0-9 ]+/); 
Shawn Li
  • 53
  • 1
  • 11
  • 1
    While this may be a valid answer, you are much more likely to help others by explaining what the code does and how it works. Code-only answers tend to receive less positive attention and aren't as useful as other answers. – Aurora0001 Nov 24 '16 at 16:48