A regular expression pattern can be used as a variable and passed to a method, e.g. match or replace.
Using literal
Here's an example - a varaible re - a literal regex pattern for parsing RGB color is passed to a match method.
var re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/; var ma = "rgb(233,23,23)".match(re);
This is the easist way.
Using Regexp Object
Of course, you have another way - using RegExp object. This way the regular expression pattern must be written in a string because RegExp object only accepts string.
var re = new RegExp( '^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$'); var ma = "rgb(233,23,23)".match(re);
Someone could have noticed I added another backslash before original backslash in the string of the regular expression. The 1st backslash is used to insert a special character (here a backslash) into the string so that a backslash is still in the pattern of the regular expression.
Variable in regexp
This method can be used when you need to pass a variable as part of a regular expression pattern to a function.
var txt = "(\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})"; function checkrgb(txt){ var re = new RegExp( '^rgb\\('+txt+'\\)$'); var ma = "rgb(233,23,23)".match(re); }