How to use variable inside regex in JavaScript? [SOLVED]


JavaScript

Introduction

A regular expression is a powerful tool for matching text patterns. They can be used for searching, editing, and manipulating text. Furthermore, regular expressions are often used in search engines, text editors, and programming languages. They are also used in many different applications, such as validating email addresses and credit card numbers.

Regular expressions (regex) can be very simple or very complex, depending on what you want to match. For example, the regular expression "a" will match any single character, while the regular expression "a+" will match one or more characters.

Instead of directly specifying the characters we want to match, we can make the regex dynamically by accepting a variable containing the characters. In this article, we will discuss how to place a variable inside regex within the JavaScript environment.

 

Use RegExp to place a variable inside regex

If you need to use a variable in a regular expression in JavaScript, you have to use the RegExp constructor. This is because the regular expression is compiled when the constructor is called, and the variable won't be replaced if you use a literal regular expression.

The RegExp constructor takes two parameters: the first is the regular expression itself, and the second is the flags parameter. The flags parameter is optional, and it can be used to set various flags on the regular expression, such as whether or not it is case-sensitive.

To use a variable in a regular expression, you have to make use of template literals and put the variable name inside of curly brackets which are preceded by a $ sign. For example, if you have a variable named name and you want to match it against the regular expression gi, you would use the following code:

let inputString = "I'm John, or johnny, but I prefer john.";
let name = "John";
let re = new RegExp(`\\\\b${name}\\\\b`, "gi");
console.log(inputString.replace(re, "Jack"));

Output

I'm Jack, or johnny, but I prefer Jack.

If the variable name contains the value "John", the regular expression would match the string "John" and will still match the string "john".

Still use the RegExp constructor, we can try something a little different, and make use of a different pattern. Here, we want to only replace when pattern is matched and not Pattern.

let str = "pattern";
let re = new RegExp(str, "g");
console.log("pattern matching".replace(re, "regex"));

Output

regex matching

However, if the str binding contained Pattern, it wouldn’t replace and will log pattern matching.

 

Summary

Regular expressions (regex) can be very simple or very complex, depending on what you want to match. There are many different ways to create regular expressions, but they all follow a similar format. The basic format of a regular expression is a series of characters that you want to match, followed by a series of characters that you do not want to match. But with a variable inside regex, we can dynamically change the words we want to replace or change or find. To achieve this, we can make use of the RegExp constructor.

 

References

Template literals (Template strings) - JavaScript | MDN (mozilla.org)
RegExp() constructor - JavaScript | MDN (mozilla.org)
javascript - How do you use a variable in a regular expression?

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment