While following the Javascript Masterclass, some examples poped up about using prototype on native objects. An implementation of curry was added to javascript, just as some other usefull features. This reminded me of a prototype a colleague of mine ones made for a format function. Format does replace values in a string. A bit like php where $myvar in “this $myvar is replaced” will be replaced by the value of $myvar. Something similar can also be found in c#.


String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");

The format implementation in javascript might look something like:


/**
 *  "this is {0} example of format: this prints abc:  {1}, 
 *  and this def: {2}".format(mystring,1,"abc","def");
 */
String.prototype.format = function(){
	var formatted = this;
        var length = arguments.length;
	// Replace string patterns by values.
	for (var i = 0; i < length ; i++){
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
	    formatted = formatted.replace(regexp, arguments[i]);
	}
	
	// Return formatted string.
	return formatted;
};
"this is {0} example of format: this prints abc:  {1}, and this def: {2}".format(1,"abc","def");

Doglas Crockford made something similar:
copied from: http://javascript.crockford.com/remedial.html
supplant(object)

supplant() does variable substitution on the string. It scans through the string looking for expressions enclosed in { } braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats. This is useful for automatically fixing URLs. So
param = {domain: ‘valvion.com’, media: ‘http://media.valvion.com/’};
url = “{media}logo.gif”.supplant(param);
produces a url containing “http://media.valvion.com/logo.gif”.


if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

Related Blogs

  • Related Blogs on

Leave a Reply

Your email address will not be published. Required fields are marked *