skip to Main Content

I have string

const message = "component="${component.name}" and id=${id}";

I have data

const data = {"id": 101, "component": { "name": "Shiv" }};

How to parse this string message, so that "${component.name}" is replaced by "Shiv" and "id" with 100,

I tried using handlebars.js but it is not compatible with my react setup

2

Answers


  1. you can simply use regular expression to do that like so:

    const replacePlaceholders = (message, data) => {
    // add your expression to match the required pattern
    const regex = /${(.*?)}/g;
    
    const replacedMessage = message.replace(regex, (match, variableName) => {
      return data[variableName] || match; // Use the value from data or the original placeholder if not found
    });
    
    return replacedMessage;
    };
    
    Login or Signup to reply.
  2. Have you tried using javascript template literals?

    If it should be dynamic, you can have a function as follows

    const renderMessage = (data)=>{
       return `component="${data.component.name}" and id=${data.id}`
    }
    const data = {"id": 101, "component": { "name": "Shiv" }};
    
    renderMessage(data) 
    //output is: 'component="Shiv" and id=101'
    
    

    Should get you going on the correct path anyway

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search