Automate Placeholder Replacement with Custom Data Models

Introduction

In modern web development, dynamically generating text content based on user data is a common requirement. Whether it's personalizing emails, generating reports, or populating templates, the ability to replace placeholders with actual data is invaluable. In this article, we will explore a TypeScript function that replaces placeholders within a string with values from a data model. This function simplifies the process of dynamic content generation, ensuring that your applications can deliver personalized and accurate information to users.

Use cases

The function can be utilized in various scenarios, such as

  1. Email personalization: Customize email templates by inserting user-specific information like names, addresses, and purchase details.
  2. Report generation: Generate dynamic reports where placeholders are replaced with real-time data fetched from a database or API.
  3. Content management systems: Enable content creators to use placeholders in templates that are dynamically populated with data when the content is rendered.
  4. Angular and react applications: Use this function to dynamically insert data into component templates, enhancing the flexibility and interactivity of your applications.

Step by step executing the Function


Step 1. Understand the Function

The replaceDataParameters function takes two parameters:

  • OriginalText: The string containing placeholders.
  • Data: The data model contains values to replace the placeholders.

Note. If the data we require based on the placeholder is not present in the data model, it returns the original placeholder.

The function uses a regular expression to find placeholders in the format [[Data.Key.SubKey]] and replaces them with corresponding values from the data object.

function replaceDataParameters(originalText: string, data) {
    const placeholderRegex = /\[\[([\w.]+)\]\]/g;
    const replacedString = originalText.replace(placeholderRegex, (match, key) => {
        const keys = key.split('.').slice(1);
        if (keys.length > 0) {
            let value: any = data;
            for (const k of keys) {
                value = value[k];
                if (value === undefined) break;
            }
            return value !== undefined ? value : match;
        } else {
            return match;
        }
    });
    return replacedString;
}

Step 2. Prepare your data model

Create a data model that holds the values you want to insert into your text. For example.

const Data = {
    UserDetails: {
        Name: "Max",
        MobileNo: 222222,
        Age: 24
    }
};

Step 3. Define your template text

Create a string that includes placeholders corresponding to the keys in your data model. This can be anything from the Backend Database as well For example.

const templateText = "Hi, My name is [[Data.UserDetails.Name]]. I'm [[Data.UserDetails.Age]] years old. My Mobile Number is [[Data.UserDetails.MobileNo]].";

Step 4. Replace placeholders with data

Call the replaceDataParameters function, passing in your template text and data model.

const resultText = replaceDataParameters(templateText, Data);
console.log(resultText);

Full code

const Data = {
    UserDetails: {
        Name: "Max",
        MobileNo: 222222,
        Age: 24
    }
};
function replaceDataParameters(originalText: string, data) {
    const placeholderRegex = /\[\[([\w.]+)\]\]/g;
    const replacedString = originalText.replace(placeholderRegex, (match, key) => {
        const keys = key.split('.').slice(1);
        if (keys.length > 0) {
            let value: any = data;
            for (const k of keys) {
                value = value[k];
                if (value === undefined) break;
            }
            return value !== undefined ? value : match;
        } else {
            return match;
        }
    });
    return replacedString;
}
const templateText = "Hi, My name is [[Data.UserDetails.Name]]. I'm [[Data.UserDetails.Age]] years old. My Mobile Number is [[Data.UserDetails.MobileNo]].";
const resultText = replaceDataParameters(templateText, Data);
console.log(resultText);

This will output.

Hi, My name is Max. I'm 24 years old. My Mobile Number is 222222.

Here below, typescript is converted into javascript and then executed.

Replacement parameter

Conclusion

By leveraging this function, you can easily replace placeholders in text with actual data from a structured model. This approach is highly flexible and can be applied to various use cases such as email personalization, report generation, and dynamic content creation. With this technique, you can ensure that your applications deliver personalized and accurate information, enhancing user experience and engagement.


Similar Articles