I'm trying to check whether the number the user provided on the frontend matches my RegExp, as seen in the code below:
var patt = new RegExp("^((?:\+27|27)|0)(\d{9})\$");
if(!patt.test($('#phoneNumber').val())){
this.error = "Please enter a valid number.";
return;
}
However, I get this error in my console:
SyntaxError: Invalid regular expression: /^((?:+27|27)|0)(d{9})$/:Nothing to repeat
I tried multiple escape approaches, but was unsuccessful.
Can someone please assist, or just show me the ropes on this?
Thanks in advance.
If you create a regexp from string you should use \\
instead of every \
(since when you create a string a single backslash is an escape character, and double backslash is a simple backslash)
Likewise if you try: console.log('\')
vs console.log('\\')
, for the first one you'll get the following error: Invalid or unexpected token
This is the full code:
var patt = new RegExp('^((?:\\+27|27)|0)(\\d{9})$');
if(!patt.test($('#phoneNumber').val())){
this.error = "Please enter a valid number.";
return;
}
You can achieve the same result with the following way (please note this time you don't create a string and then a regexp from the string, rather you create a regexp directly, so you don't need an escape backslash before every backslash):
var patt = /^((?:\+27|27)|0)(\d{9})$/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments