0

So we have the classic example of interpolation like this:

const AGE = 25;
let result = `I'm ${AGE} years old!`;

What I am trying to achieve though is replace in a string I access through a variable, not directly. I never know how many items I must replace. Example:

const Item_Required = "The {item} is required and needs to be between {min} and {max} {unit}!"
const ContractTitle = "Contract Title"
const Unit_Characters = "characters";
let result = Item_Required
.replace("{item}", ContractTitle)
.replace("{min}", 3)
.replace("{max}", 100)
.replace("{unit}", Unit_Characters );

Is there a more direct and nice way to do this? Or is this the way to go?

Anamaria Miehs
  • 521
  • 1
  • 4
  • 10
  • If you know what keywords will be used as placeholders, you can search your string for the `{keyword}` pattern, flagging which ones are used, then loop over those to replace. – mykaf Aug 10 '22 at 13:33
  • Duplicate of [JavaScript template literals substitute variable later (before values are known)](https://stackoverflow.com/questions/71082437/javascript-template-literals-substitute-variable-later-before-values-are-known) – Samathingamajig Aug 10 '22 at 13:35
  • You could put the key values into an object (eg, `obj["item"] = 'Contract Title'`) and roll with this oneliner: `s = s.replace(/\$\{(.+?)\}/g, function(x, m1) {return obj[m1]});` – Barry Carter Aug 10 '22 at 13:36
  • Does this answer your question? [How can I do string interpolation in JavaScript?](https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript) – evolutionxbox Aug 10 '22 at 13:43

2 Answers2

1

Easy with regexp replacement, you can use the code you prefer, but this code must no appear in the string for example ${...}

const str = "The ${item} is required and needs to be between ${min} and ${max} ${unit}!"
const replacements={
    item : "Contract Title",
    unit : "characters",
    min: 3,
    max: 100,
}
const str2 = str.replace(/\$\{\w+\}/g, function(all) {
   return replacements[all.substring(2,all.length-1)] || all;
});
console.log(str)
console.log(str2);
Edoldin
  • 160
  • 6
0

JavaScript supports Tagged Template Literals. Native in ES6 is the String.raw built-in Tag function. But you can in fact create your own Tagged functions and process the template literal interpolation expressions as you see fit:

const age = 25;
const min = 20;
const max = 30;

function ageTag(literals, age, min, max) {
  console.log(literals); // an array of literal strings in the template
  console.log(age); // first expression
  console.log(min); // second expression      
  console.log(max); // third expression

  if(age == 25) {
    age = 35
  }

  return `${literals[0]} really ${realAge}`;
} 

ageTag`my age is ${age} and the min allowed is ${min} and the max allowed is ${max}`

// =>
[
  'my age is ',
  ' and the min allowed is ',
  ' and the max allowed is ',
  ''
]
25
20
30
'my age is really 35'
Daniel Viglione
  • 8,014
  • 9
  • 67
  • 101