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.

3
  • 1
    This might also be good to look at stackoverflow.com/questions/29182244/…. An approach other than find & replace is using eval, but that has its own drawbacks. Commented Jul 16, 2020 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. Commented Jul 16, 2020 at 10:11
  • Does this answer your question? Convert a string to a template string Commented Jul 16, 2020 at 10:45

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Can't I change whole string into interpolated string? Or the regex is the only option here
@HarishSharma There are multiple ways, regex is just one. You could add a method to the string prototype (See this post). Another option is to use eval() but it's highly discouraged, so please DON'T use it (MDN eval).
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
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);

3 Comments

Can't I change whole string into interpolated string? Or the regex is the only option here...
yes.eval is not recommended to use & discouraged .so regex is the option will work to match the string
Thanks for the answer. I accepted the answer from @theblackgigant, because he posted earlier.
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 = "[email protected]";

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

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

console.log(parse(response));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.