Clue Mediator

How to use a variable in Regular Expression pattern in JavaScript

📅March 25, 2022

In this article, we’ll show you how to use a variable in a Regular Expression pattern in JavaScript.

Checkout more articles on JavaScript

Here, we will refer to this article to understand the use case. In this article, we used the `/is/g` to replace the string. But now suppose if we have `is` string in the variable then we will see how to use the variable in Regular Expression.

For building a regex pattern from a dynamic string, we can use the JavaScript RegExp object.

function handleReplaceAll() {
  var replaceStr = 'is';
  var sentence = 'This is test example and it Is easy to learn.';

  var re = new RegExp(replaceStr, 'g');
  var output = sentence.replace(re, '-'); // Output: Th- - test example and it Is easy to learn.

  document.getElementById("demo").innerHTML = output;
}

Now if you want to replace the case insensitive string then you have to use `gi` flag. Checkout the below example.

function handleReplaceAllCI() {
  var replaceStr = 'is';
  var sentence = 'This is test example and it Is easy to learn.';

  var re = new RegExp(replaceStr, 'gi');
  var output = sentence.replace(re, '-'); // Output: Th- - test example and it - easy to learn.

  document.getElementById("demo").innerHTML = output;
}

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂