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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:


full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.