Sunday, July 14, 2024
HomeLanguagesJavascriptConvert user input string into regular expression using JavaScript

Convert user input string into regular expression using JavaScript

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:

 

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments