Convert user input string into regular expression using JavaScript
Regular expressions (RegExp) are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. There are two ways to construct a regular expression in JavaScript .
- 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"
Javascript
<script> const str = "Geeks for Geeks" ; // Input from User const regex = prompt( "Enter RegExp" ); // Conversion from string to RegExp const reg = new RegExp(regex, "g" ); // The match fn returns the array of strings // That match to RegExp const result = str.match(reg); if (result) console.log(result); else console.log( "Not Found" ); </script> |
Output: