JavaScript: RegExp Constructor
new RegExp(args)
-
same as
RegExp(args)
RegExp(str, flagsStr)
-
Create a RegExp Object from string.
See also: • RegExp Syntax • RegExp 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
- RegExp Tutorial
- RegExp Functions
- RegExp Syntax
- RegExp Flags
- Replacement String Dollar Sign Sequence
- Replacement Function Arguments