JavaScript: 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 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


BUY
ΣJS
JavaScript in Depth

JS Obj Reference

RegExp

prototype

Syntax

misc