-2
const sentence = ' Name: ${fname} ${lname} </br> Email: ${email} </br> ' 

let valuesObj={
  "fname": "sant",
  "lname": "G",
  "email": "Test@test.com"
}

tried this code but no use:

function replaceAll(str, map){
  for(key in map){
    str = str.replaceAll(key, map[key]);
  }
  return str;
}

var newString = replaceAll(sentence , valuesObj);

console.log(newString)

Expected out put is :

Name: sant G

Email:Test@test.com

how to do this Using NodeJs or Javascript

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
ssantug
  • 11
  • 4

2 Answers2

1

Do not use replace functions here. Do instead:

const valuesObj = {
  fname: 'sant',
  lname: 'G',
  email: 'Test@test.com'
};

const sentence = `Name: ${valuesObj.fname} ${valuesObj.lname} </br> Email: ${valuesObj.email} </br>`;

If your string is created dynamically, you are looking for a behavior similar to this.

Jean-Baptiste Martin
  • 1,399
  • 1
  • 10
  • 19
0

You forgot the dollar symbol ($) and the brackets ({...}) in your replace method:

const sentence = ' Name: ${fname} ${lname} </br> Email: ${email} </br> ';

const valuesObj = {
  "fname": "sant",
  "lname": "G",
  "email": "Test@test.com"
};

function replaceAll(str, map) {
  return Object.entries(map).reduce((s, [key, value]) => s.replaceAll(`\${${key}}`, value), str);
}

const newString = replaceAll(sentence, valuesObj);

console.log(newString);
jabaa
  • 5,844
  • 3
  • 9
  • 30