Squiffy: Basic Javascript Help

pzolla
I was wondering if someone could assist in explaining something. I am learning JavaScript and am working my way through the Squiffy code. This function:

String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};

What I believe I understand is that this is a method added to the String prototype that assigns the arguments object which delivers the arguments in an 'array-esque' style where you can use index to reference but it is not an array. It then looks at the string and replaces everything between the { } with the unnamed function. Within the function I understand that it is basically returns the result of an 'if then else' statement'.

What I am struggling with is where the values of (match, number) originate from? If I console them out they are {0} and (0).

I know I am missing something at a pretty basic level and would appreciate if someone could point me in the right direction.

Alex
That code is actually from here: http://stackoverflow.com/questions/6104 ... ing-format

It's a JavaScript implementation of something like string.Format which exists in C#. It makes it easier to interpolate strings. For example, if I wanted to greet somebody by their first and last name, and tell them their age, normally I would have to do something like this...


var greeting = "Hello " + firstName + " " + lastName + ", you are " + age + ".";


By adding this "format" function to strings, I can do it like this:


var greeting = "Hello {0} {1}, you are {2}".format(firstName, lastName, age);


The way it works is: the variable "args" is an array of all arguments passed to the format function. So in the example above, the array is [firstName, lastName, age]. Then it calls this.replace with a regular expression that finds digits inside braces. It runs a function for every occurrence, and this function pulls the relevant value out of the arguments array.

The latest version of JavaScript allows for template strings (http://tc39wiki.calculist.org/es6/template-strings/), so in the future we'll be able to do this easily without having to create our own format function.

This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums