Nika Kurashvili
Nika Kurashvili

Reputation: 6472

how do I replace dynamic variables which are unknown dynamically

I have a .js file which has config structure something like this.

genGetLocations:{
   data_url:'restaurants/{var1}/tables/{var2},
}

THis is one example. Some might have config that has data_url which has more than two dynamic variables. Then in .vue file, after getting the data_url, i will have two ids which have to be replaced into var1 and var2 so that I will have the final rest api url to make the request to.

Problem: I don't know how many variables each data_url is going to have and where they are going to be placed in data_url. So, in .vue files, when I will have the ids, i want to replace them in data_url.

Upvotes: 2

Views: 173

Answers (3)

amitic
amitic

Reputation: 21

Depending on whether your IDs are in an array or an object, you could do one of the following:

const data = 'restaurants/{var1}/tables/{var2}';
const idsArray = [101, 102];

console.log(
  data.replace(/\{var(\d+)\}/g, (substr, idx) => idsArray[parseInt(idx) - 1])
);

const data = 'restaurants/{var1}/tables/{var2}';
const idsObj = {
  var1: 101,
  var2: 102
};

console.log(
  data.replace(/\{(var\d+)\}/g, (substr, key) => idsObj[key])
);

If you want the keys to be arbitrary:

const data = 'restaurants/{foo}/tables/{bar}';
const idsObj = {
  foo: 101,
  bar: 102
};

console.log(
  data.replace(/\{(.*?)\}/g, (substr, key) => idsObj[key])
);

Upvotes: 2

Tom Marienfeld
Tom Marienfeld

Reputation: 716

This is looking for every {} in your URL. So it could be {var1}, {string2} or so.

Try this:

var info = {"genGetLocations":{
   "data_url" : "restaurants/{var1}/tables/{var2}"
}};

var ids = ["test1", "test2", "test3"];
var regexp = /\{.*?\}/g;
var results = info.genGetLocations.data_url.match(regexp);
var replacedString = info.genGetLocations.data_url;
results.forEach(function(result, index) {
  replacedString = replacedString.replace(new RegExp(result,"g"), ids[index]); 
});

console.log(replacedString);

Upvotes: 1

PraveenKumar S
PraveenKumar S

Reputation: 250

May be you can try this

String.prototype.formatUnicorn = String.prototype.formatUnicorn || function () {
    	var e = this.toString();
    	if (!arguments.length)
    		return e;
    	var t = typeof arguments[0],
    	n = "string" == t || "number" == t ? Array.prototype.slice.call(arguments) : arguments[0];
    	for (var i in n)
    		e = e.replace(new RegExp("\\{" + i + "\\}", "gi"), n[i]);
    	return e
    }
    
    /** Lets Assume your Code 
    genGetLocations:{
   data_url:'restaurants/{var1}/tables/{var2},
}**/
console.log('restaurants/{var1}/tables/{var2}'.formatUnicorn({'var1':'test1','var2':'test2'}))

Upvotes: 0

Related Questions