Convert a User Input String into a Regular Expression using JavaScript

Last Updated : 8 Sep, 2026

JavaScript allows a user-provided string to be converted into a regular expression using the RegExp constructor. This is useful when the pattern needs to be determined dynamically at runtime.

  • Use the RegExp constructor to create a regular expressions from a string.
  • Use the constructor when the regular expression pattern is provided dynamically by the user.
  • Apply flags such as g to control how the pattern matches the input string.

Approach 1: Using the RegExp Constructor with match()

The RegExp constructor accepts a string containing a regular expression pattern and optionally accepts flags. Since the pattern is provided dynamically by the user, the constructor is suitable for creating the regular expression at runtime.

Example: In this example, the user enters a regular expression pattern, which is converted into a RegExp object and used with match() to find matching strings.

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() method returns the strings
// that match the regular expression
const result = str.match(reg);

if (result) {
    console.log(result);
} else {
    console.log("Not Found");
}

Output:

Approach 2: Using the RegExp Constructor Directly

The RegExp constructor can also be used to convert user input into a regular expression object without immediately applying it to a string.

Example: In this example, the user enters a regular expression pattern, which is passed directly to the RegExp constructor.

JavaScript
const userInput =
    prompt("Enter a regular expression pattern:");

const regex = new RegExp(userInput);

console.log(regex);

Output:

Comment