- 1. Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows.
const reg = /ab+/;
- 2. Calling the constructor function of the RegExp object, as follows.
const reg = new RegExp('ab+', flag);
Using the constructor function provides run time compilation of the regular expression, hence we should use the second method here as the string is a dynamic input from the user. Both the above expressions correspond to the same RegExp.
Example: For the string we will take “Geeks For Geeks'”.
Input : '^Ge' Output: ["Ge"] 0: "Ge" Input : '[A-z]+' Output: (3) ["Geeks", "For", "Geeks"] 0: "Geeks" 1: "For" 2: "Geeks"