5

I'm receiving a string from the backend. Let's say

"Save Earth, ${name}"

At the frontend, I'm using javascript I want to know how can I bind name from the variable getting in the string.

I know about the string interpolation in JS like below

`Save Earth, ${name}`

Even on using string interpolation is not helping me and I'm getting normal string from backend like below:

  const name = "John"; 
  const response = "Save Earth, ${name}";
  console.log(`${response}`);

What I am getting

"Save Earth, ${name}"

Expected

"Save Earth, John"

NOTE: I can't use string find & replace method because the variable name can be anything.

EDIT: Do I need to use Regex to find & replace method only here.

Why I am looking for another approach? Because the string can be lengthy and I feel that will increase the time complexity.

Vijay Palaskar
  • 526
  • 5
  • 15
harish kumar
  • 1,732
  • 1
  • 10
  • 21
  • 1
    This might also be good to look at https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string. An approach other than find & replace is using `eval`, but that has its own drawbacks. – 5eb Jul 16 '20 at 10:10
  • @BasvanderLinden Yes, I was avoiding `eval` till now. But i'll try to brainstorm little bit on it, if it can be an optimized solution. – harish kumar Jul 16 '20 at 10:11
  • Does this answer your question? [Convert a string to a template string](https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string) – Vijay Palaskar Jul 16 '20 at 10:45

3 Answers3

3

Find & replace can stil be used with a regex.

You could use an object instead of seperate variables with the data you have what to replace. Then inside the replace function you can pass a function as second parameter which returns the correct data.

The reason for an object is that we can't access variables by name (unless you add them to the window object).

const response = "${name} is ${age} years old!";

const data = {
  name: "John Doe",
  age: "42"
};

const replaceVariable = (match, inner) => {
  return data[inner] || "";
}

const replaced = response.replace(/\$\{(\w+)\}/gi, replaceVariable);

console.log(replaced);
Reyno
  • 6,119
  • 18
  • 27
  • Can't I change whole string into interpolated string? Or the regex is the only option here – harish kumar Jul 16 '20 at 10:05
  • @HarishSharma There are multiple ways, regex is just one. You could add a method to the string prototype ([See this post](https://stackoverflow.com/a/41015840/3257622)). Another option is to use `eval()` but it's highly discouraged, so please DON'T use it ([MDN eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!)). – Reyno Jul 16 '20 at 10:11
  • Yes, I was avoiding `eval` for this and I was looking for `time complexity` purpose because the string can be large. I'm accepting `regex` for now. Thanks for the answer – harish kumar Jul 16 '20 at 10:15
3

For this you need use replace function with regex With /${\w+}/ variable what have you defined.

const name = "John";
const response = "Save Earth, ${name}";

const newResponse = response.replace(/\${\w+}/ ,name);

console.log(newResponse);
Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56
Vijay Palaskar
  • 526
  • 5
  • 15
0

I am afraid that you may use regex for solving this problem. Get the variable names using regex and declare the variables using var keyword.

The var keyword put the values into window object so that your can fetch them from window.

You can follow this code-

var name = "John"; 
var email = "hello@example.com";

const response = "Save Earth, ${name} ${email}";

const parse = str => str.replace(/\${(.+?)\}/gm, (match, varName) => window[varName]);

console.log(parse(response));
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30