0

So my previous question was pretty bad so I am editing this question.

I have object/json like this

{
"title": "Hello {USER}",
"description": "Today you earned {AMOUNT} dolars
}

I'm sending this data to api so it gives returns an special message. But the problem is I need to replace {USER} and {AMOUNT} without needing to get values, change it and reassign it or etc. It's like replace but for objects so without changing object and doing complicated things I can dynamicly change {USER} and {AMOUNT} User comes from the api and AMOUNT is a random number I just need to change the {} brackets without complicating things too much

İspik
  • 21
  • 6
  • 1
    Where do the values come from? – epascarello May 10 '21 at 15:17
  • 3
    https://stackoverflow.com/questions/2780074/find-and-replace-tokens-in-javascript – epascarello May 10 '21 at 15:18
  • @epascarello the values would be most likely change I just need to replace them however I want – İspik May 10 '21 at 15:19
  • [Replacing Text Inside of Curley Braces JavaScript](https://stackoverflow.com/a/54937047/3082296) – adiga May 10 '21 at 15:24
  • With minimal risk, you may be able to do the search and replace on the entire JSON string without converting it to a JavaScript object. Can you be clear...is this really starting as a JSON string or is it starting as a JavaScript object? – Wyck May 10 '21 at 15:27
  • 1
    Your question is unclear. Do you want to show this string with one value. Or do you want to show the string with changing values. Option one use replace but that can only be done once. –  May 10 '21 at 15:28

3 Answers3

2

String.prototype.replaceAll()

Returns

a new string, with all matches of a pattern replaced by a replacement.

var obj = {
"title": "Hello {USER}",
"status": "You look {STATUS} today"
};
function replaceTokens(name, value, str){
  return str.replaceAll("{"+name+"}", value);
}
obj.title = replaceTokens("USER", "Mark", obj.title);
obj.status = replaceTokens("STATUS", "great", obj.status);
console.log(obj);
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

You can use a regex to replace the text in curly braces :

function replaceText(text, value) {
  const regex = /\{.*\}/;
  return text.replace(regex, value);
}

const TEXT = 'Hello {USER}';
console.log(replaceText(TEXT, 'Mark'));
lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • This technique is much more likely to get confused by stray braces that do not conform to the syntax of the string interpolation. – Wyck May 10 '21 at 16:07
  • That depends on the scope where it is going to be applied. I think for small strings it would not be a problem. – lissettdm May 10 '21 at 16:13
1

Here's an approach that uses a regular expression to locate {KEY} and looks up KEY in a dictionary to perform the replacement. I used a conservative syntax of A-Z plus underscore for the syntax of the key names.

This version returns a new object (does not change the original object).

function interpolateObject(obj, dict) {
  return Object.fromEntries(Object.entries(obj).map(interpolateEntry));
}

function interpolateEntry([key, val]) {
  if (typeof val !== 'string') return [key, val];
  return [key, interpolateString(val, dict)];
}

function interpolateString(str, dict) {
  return str.replace(/\{([A-Z_]+)\}/g, (original, key) => dict.hasOwnProperty(key) ? dict[key] : original);
}

const template = {
  "title": "Hello {USER}",
  "status": "You look {STATUS} today",
};
const dict = { USER: 'Mark', STATUS: 'great' };
console.log(interpolateObject(template, dict));

You could also write a version that modifies the object in-place if that's what's needed.

// Alternate approach, modifies object in place.
function interpolateObjMutate(obj, dict) {
  for (const key in obj) {
    if (typeof obj[key] === 'string') obj[key] = interpolateString(obj[key], dict);
  }
}
Wyck
  • 10,311
  • 6
  • 39
  • 60
  • I need to use this on multiple folders and to do that I need to write that again and if I export it I will get dict is not defined from interpolateEntry as dict is not defined and I kinda can't find a way to get over this im still not that good at js apperantly – İspik May 10 '21 at 18:16