how I convert string into interpolated string?

Viewed 476

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.

3 Answers

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);

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);

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));

Related