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.

console.log("aa".replace(RegExp("a", "g"), "b") === "bb");
// true

🟢 TIP: be sure to use double backslash in string. 〔see JS: String Escape Sequence

// replace digits by x.
console.log("8314".replace(RegExp("\\d+"), "x") === "x");
// true

When Arg is regex object

if the first arg is using slash syntax, it is already a regex object, still works:

// the argument /a/g is already a regex object
console.log("aa".replace(RegExp(/a/g), "b") === "bb");
// true

// above is same as
console.log("aa".replace(RegExp(RegExp("a", "g"), "g"), "b") === "bb");
// true

JavaScript. Regular Expression