How to use JavaScript Regex both literal notation and regexp object constructor method with examples

Regular Expressions provide a powerful way to extract information from text content.   Regular Expressions or Regex can be used to search text and find matches on the search pattern.   The returned results are the matches from the text on the search pattern provided.  The search pattern can get fairly complex, this chapter is designed to provide a simple introduction to extracting results from text blocks.

The regular expression patterns can be used within a number of JavaScript methods, to check for matches and do something within the code.  In JavaScript you can create the regular expression in two ways, either with a regular expression literal, where the pattern is nested between two forward slashes or using the constructor object which requires a pattern as a string argument.  If you expect the pattern to change or are receiving the pattern from an external source use the constructor.

Regular expression literal

const myPattern1 = /a/;

RegExp constructor object

const myPattern2 = new RegExp(‘a’);