Luca Casonato
Luca Casonato

Reputation: 386

Replacing a substring of a variablename of a string with a variable

I have a variable, called String that has a tag in it called bar.var String = "Foo <Object.1>" and I have an object called Object, var Object = {1:"Bar",2:"More Bar",3:"Even more Bar"}, and now I need the tag Object.1 to get replaced by the so I end up with something like this:var String = "Foo Bar"

Here is the catch: I might have multiple (and different) tags in one string, and I never know which and how many tags I have in that string, and also there could be millions of variables inside of the object.

Calls for help, Luca

Upvotes: 1

Views: 583

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using String.prototype.replace() function:

var str = "Foo <Object.1> some text, <Object.2> data, <Object.3> other",
    values = {1:"Bar", 2:"More Bar", 3:"Even more Bar"};

str = str.replace(/<Object\.(\d+)>/g, function (m0, m1) {
  return (values[m1])? values[m1] : m0;  // replace if `Object` number exists as a key of predefined `values` object
});

console.log(str);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386520

You could use, with proper variable names and a global variable for the replacment object, String#replace with an access over the window object and keys, taken from the string.

var string = "Foo <object.1>",
    object = { 1: "Bar", 2: "More Bar", 3: "Even more Bar" };

string = string.replace(/<([^.]+)\.([^>]+)>/, function (_, v, k) {
    return window[v][k];
});

console.log(string);

A better approach, would be to store the replacement parts into an object and take the parts as keys, without using the window object. Then the object could be local as well.

var string = "Foo <object.1>",
    values = { object: { 1: "Bar", 2: "More Bar", 3: "Even more Bar" } };

string = string.replace(/<([^.]+)\.([^>]+)>/, function (_, k1, k2) {
    return values[k1][k2];
});

console.log(string);

Upvotes: 3

Related Questions