JavaScript Regular expressions Creating a RegExp Object


Standard Creation

It is recommended to use this form only when creating regex from dynamic variables.

Use when the expression may change or the expression is user generated.

var re = new RegExp(".*");

With flags:

var re = new RegExp(".*", "gmi");

With a backslash: (this must be escaped because the regex is specified with a string)

var re = new RegExp("\\w*");

Static initialization

Use when you know the regular expression will not change, and you know what the expression is before runtime.

var re = /.*/;

With flags:

var re = /.*/gmi;

With a backslash: (this should not be escaped because the regex is specified in a literal)

var re = /\w*/;