JS: RegExp Constructor

By Xah Lee. Date: . Last updated: .
new RegExp(args)

same as RegExp(args)

RegExp(patternStr, flagsStr)
  • patternStr is a string or regex object.
  • flagsStr is Regex Flags

Create a regex object from string.

const myregex = RegExp("a", "g");
console.log(myregex);
// /a/g

console.log("aa".replace(myregex, "b"));
// bb

Example. double slash and String.raw

🟢 tip: if your regex pattern contains backslash, you need double backslash in string. [see JS: String Escape Sequence] or use String.raw

// replace digits by x.
// demo example of using String.raw to avoid double backslash.

console.assert(
 "8314".replace(RegExp("\\d+"), "x") ===
  "x",
);

// same as

console.assert(
 "8314".replace(RegExp(String.raw`\d+`), "x") ===
  "x",
);