Dynamically replace data based on matched RegEx - JavaScript?

Regex (Regular Expressions) is used to match patterns in strings of text. With JavaScript, you can use regex to dynamically replace data based on matched patterns using the replace() method.

This article will explain how to use regex and JavaScript together to make dynamic replacements in your code. We'll cover the basics of regex syntax and practical examples for template replacement.

Using replace() Method

The replace() method in JavaScript searches a string for a specified value or regular expression and returns a new string with replacements. The original string remains unchanged.

Syntax

string.replace(searchValue, newValue)
string.replace(regexPattern, replacementFunction)

Example 1: Template Replacement with Hash Syntax

In this example, we use a regex pattern to replace placeholders wrapped in hash symbols (#) with actual values from a replacement object.

<!DOCTYPE html>
<html>
<body>
   <p id="result1"></p>
   <script>
      const original = "#T1# to the #T2# the #T3# E-way learning";
      const replacements = {
         T1: "Welcome",
         T2: "Tutorialspoint",
         T3: "Best"
      };
      
      const afterChange = original.replace(/#([^#]+)#/g, (match, key) => {
         return replacements[key] !== undefined ? replacements[key] : match;
      });
      
      document.getElementById("result1").innerHTML = 
         "Original: " + original + "<br>" +
         "After change: " + afterChange;
   </script>
</body>
</html>

Example 2: Dynamic Address Replacement

This example demonstrates replacing numbered address placeholders with corresponding values from an object.

<!DOCTYPE html>
<html>
<body>
   <p id="result2"></p>
   <script>
      var addressData = {
         "address_1": "Yes",
         "address_2": "Hyderabad", 
         "address_10": "Permanent"
      };
      
      var sentence = `Can I Know The Address: #ADDRESS1# You Are From: #ADDRESS2# Is It Current Or Permanent: #ADDRESS10#`;
      
      sentence = sentence.replace(/#ADDRESS(\d+)#/g, function(match, num) {
         var value = addressData["address_" + num];
         return value ? value : match;
      });
      
      document.getElementById("result2").innerHTML = sentence;
   </script>
</body>
</html>

Example 3: Curly Brace Template Replacement

This example uses double curly braces {{}} as placeholders, commonly used in templating systems.

<!DOCTYPE html>
<html>
<body>
   <p id="result3"></p>
   <script>
      var template = `My name is {{fullName}} and I live in {{countryName}}`;
      var details = {
         "fullName": "David Miller",
         "countryName": "Australia"
      };
      
      var result = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
         return details[key.trim()] || match;
      });
      
      document.getElementById("result3").innerHTML = result;
   </script>
</body>
</html>

Key Regex Patterns Explained

Pattern Description Use Case
/#([^#]+)#/g Matches text between hash symbols Simple placeholder replacement
/#ADDRESS(\d+)#/g Matches ADDRESS followed by numbers Numbered placeholder replacement
/\{\{(.+?)\}\}/g Matches text between double curly braces Template engine style replacement

How It Works

The replacement function receives two parameters: the full match and captured groups. You can use these to look up replacement values in your data object and return the appropriate substitution.

Conclusion

Dynamic regex replacement in JavaScript provides a powerful way to create template systems and perform pattern-based string substitutions. Use replace() with regex patterns and replacement functions for flexible data interpolation.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements