Open In App

Convert user input string into regular expression using JavaScript

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object

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.

Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows.

const reg = /ab+/;

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




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");


Output:

 

Example 2: In this example, we will use the RegExp constructor.

Javascript




const userInput = prompt("Enter a regular expression pattern:");
const regex = new RegExp(userInput);
console.log(regex);


Output:

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads