Reputation: 113
It is documented that one can create regex expressions using 2 methods:
1.simple expression
/ab+c/i;
2.using a constructor
new RegExp(/ab+c/, 'i');
new RegExp('ab+c', 'i');
I have used the version RegExp(/ab+c/, 'i') which passed in Chrome, Mozilla but not in Safari, returning an error:
cannot supply flags when constructing one regexp from another
I have switched to the first method and it works now but there are 2 things that are not clear for me:
what does '/' character stand for in an expression like that. I've seen it added by default in online regex test sites
why safari failed to work with the version that i used
Upvotes: 1
Views: 4969
Reputation: 626747
The regex constructor notation (new RegExp(...)
) is mainly used when you need to pass a variable to your pattern. If the pattern is "hard-coded", use a regex literal straight away: var reg = /ab+c/i
. See more on when to use which notation here.
Safari currently does not accept a regex literal as the first argument to the RegExp
constructor, nor do some other browsers. Thus, it is safer to pass a regular string pattern as the first argument.
As for the /.../
, these are regex delimiters that delimit action/pattern/modifiers. In JS, the action part is not used, and the modifiers are limited to i
(case-insensitive), g
(global matching) and m
(multiline mode to redefine the ^
and $
behavior so that they could match the start/end of a line instead of the start/end of a string).
Upvotes: 1