The following JS regex is working as expected
/^(?:(?:(?(?:00|+)([1-4]dd|[1-9]d+))?)[-. \/]?)?((?:(?d{1,})?[-. \/]?){0,})(?:[-. \/]?(?:#|ext.?|extension|x)[-. \/]?(d+))?$/i
But when I use this as a HTML 5 pattern I got this error:
Pattern attribute value /^(?:(?:(?(?:00|+)([1-4]dd|[1-9]d+))?)[-. /]?)?((?:(?d{1,})?[-. /]?){0,})(?:[-. /]?(?:#|ext.?|extension|x)[-. /]?(d+))?$/i is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: //^(?:(?:(?(?:00|+)([1-4]dd|[1-9]d+))?)[-. /]?)?((?:(?d{1,})?[-. /]?){0,})(?:[-. /]?(?:#|ext.?|extension|x)[-. /]?(d+))?$/i/: Invalid group
The browser telling me this “Uncaught SyntaxError: Invalid regular expression. Invalid group”
Any help would be really appreciated as regex is not my real strength.
Advertisement
Answer
A regex and a regex string are two different things.
Regex example:
/[a-zA-Zd]+/.test('abc123')
Equivalent regex string example:
new RegExp('[a-zA-Z\d]+').test('abc123')
A backslash in a string escapes the character that follows. For many characters it is a no-op, as in a 'd'
string, which is equivalent to 'd'
. Hence you need to specify a double backslash to get d
that can be used in a regex string to mean a digit.
Example use in HTML5 to validate an input:
<input type="text" name="uname" pattern="[a-zA-Zd]+" minlength="4" maxlength="10" />
So in your case, make sure to escape the backslash in the regex string:
"^(?:(?:\(?(?:00|\+)...
In the pattern attribute you can’t specify the modifier i
to ignore case, e.g. you need to tweak the regex string itself to be case insensitive.
Docs on HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern