By 'variable' you mean any expression which can be coerced into a String, right? The point is to clearly make a distinction between a regex pattern (which is a string) and the RegExp instance itself:
var myString = "Hello"; var myPattern = "\\n\\d\\t[^\\t]+\\t\\d\\t" + myString; var myRegex = new RegExp(myPattern, 'g'); // myRegex is then equivalent to: /\n\d\t[^\t]+\t\d\tHello/g
Note that all regular expression metacharacters such as \n or \d must be double-escaped when you introduce them through a literal string (cf. myPattern declaration).
I would write Marc's example using this horrible construct:
var myString = "Hello";
var myPattern = /\n\d\t[^\t]+\t\d\t/.source + myString;
var myRegex = new RegExp(myPattern, 'g');
because it avoids the double-quoting.
John Hawkinson wrote:
...using this horrible construct:
Nice! I don't think I've seen that one before.