Reputation: 7997
I have the following function:
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
Now say I have the following code defined:
var dataItem = { membershipId: 1, userId: 3 };
var dataKeyNames = 'membershipId,userId';
var url = '/Admin/User?MembershipId={0}&UserId={1}';
What I'd like to do is call the format function passing in each value from the data item (for each data key name). For example if there was only one data key name then I would be able to say:
var formattedUrl = url.format(dataItem[dataKeyNames]);
But I need to be able to do a split on the dataKeyNames and pass each corresponding value from the data item in as arguments in the format function.
I'd appreciate it if someone could show me how this is done. Thanks
Upvotes: 0
Views: 89
Reputation: 50933
Let's take this one step at a time.
First, you can split the string of keys into an array, using dataKeyNames.split(",")
.
Then, you can call map
on the array of strings to generate a new array - specifically, the values that you want to pass to your format
method. This is where you interact with the dataItem
variable.
Finally, you can use url.format.apply
to actually call your format
method with the new array. Note that it's possibly most important to pass url
as the first argument to apply
- that sets the this
value that format
will use.
Here's the code I came up with:
var formattedUrl = url.format.apply(url, dataKeyNames.split(",").map(function (val, index, array) {
return dataItem[val];
}));
DEMO: http://jsfiddle.net/T4tHx/
To make it more readable, you can definitely split this up into several lines.
References:
String.prototype.split
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/splitArray.prototype.map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/mapArray.prototype.map
browser support - http://kangax.github.io/es5-compat-table/#Array.prototype.mapFunction.prototype.apply
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/applyUpvotes: 2