JavaScript: RegExp Constructor

By Xah Lee. Date: . Last updated: .
new RegExp(args)
same as RegExp(args)
RegExp(patternStr, flagsStr)
Create a RegExp Object.

For pattern syntax and flag, see: • RegExp SyntaxRegExp Flags

Examples

Using the slash syntax for pattern:

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

Using the string syntax for pattern:

const myStr = "about time";
const myRegex = RegExp("t", "g");
console.log( myStr.replace(myRegex, "_" ) );
// 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 myStr = "30 thousand";
const myRegex = RegExp("\\d+");
console.log( myStr.replace(myRegex, "_" ) );
// _ thousand

JavaScript Regular Expression

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

RegExp

prototype

Syntax

misc