JS: RegExp Constructor

By Xah Lee. Date: . Last updated: .
new RegExp(args)
same as RegExp(args)
RegExp(str, flagsStr)
Create a RegExp Object from string.
See also: • RegExp SyntaxRegExp Flag

Examples

Using the slash syntax for pattern:

const xxStr = "about time";
const xxRegex = RegExp( /t/g );
console.log( xxStr.replace(xxRegex, "_" ) );
// abou_ _ime

Using the string syntax for pattern:

const xxStr = "about time";
const xxRegex = RegExp("t", "g");
console.log( xxStr.replace(xxRegex, "_" ) );
// abou_ _ime

Double Slash

Note: when using string to construct a pattern, you need to use double backslash for any single backslash in regex. Because, single backslash is used in string to escape the next character. So, when you use double backslash, the RegExp will just get a single backslash.

const xxStr = "30 thousand";
const xxRegex = RegExp("\\d+");
console.log( xxStr.replace(xxRegex, "_" ) );
// _ thousand

JavaScript, Regular Expression