JavaScript MessageFormat - java.text.MessageFormat-like thing for "client side"

Motivation: Enable locale-agnostic handling of string constants and concatenated messages on the client side of a web application.

I needed something like this... 15 minutes of coding yielded something short and elegant (especially for those who prefer lambda calculus). Tested on IE6 and FF, went through jslint which I strongly recommend anyone.


/*jslint browser: true, white: true, undef: true, nomen: true */
/*global packages */

packages.nls = {};

packages.nls.MessageFormat = function (pattern) {
    this.pattern = pattern;
};

packages.nls.MessageFormat.prototype.format = function (data) {
    var v = typeof data === "object" ? data : [data];
    return this.pattern.replace(/\{([^{}]*)\}/g, function (a, b) {  
        var r = v[b];
        return typeof r === "undefined" ? a : r; 
    });
};

Some words about the concept: you instantiate it with a string that contains placeholders in curly brackets. Placeholders are integers or names. The 'format' method takes the properties of the passed in object and substitues the placeholders with the value of the respective properties. In the case of arrays the placeholders may refer to the position of the array elements. If the passed in object is anything else then an array or object, it is wrapped into an array. This piece of syntactic sugar enables shorthand use for format strings with a single parameter. Let us see an example:


function mftest() {
	var div = document.getElementById("mftest");
	var mf = new packages.nls.MessageFormat("nulla {0} egy {1} ketto {2} harom {3} bla"); 
	div.appendChild(document.createTextNode(mf));
	div.appendChild(document.createTextNode(mf.format(["nulla","egy","ketto","harom"]))); // nulla nulla egy egy ketto ketto harom harom bla
	div.appendChild(document.createElement("br"));
	div.appendChild(document.createTextNode(mf.format(["nulla","egy","ketto"])));         // nulla nulla egy egy ketto ketto harom {3} bla
	div.appendChild(document.createElement("br"));
	div.appendChild(document.createTextNode(mf.format(["nulla", 1.0, 3, false])));        // nulla nulla egy 1 ketto 3 harom false bla
	div.appendChild(document.createElement("br"));
	div.appendChild(document.createTextNode(mf.format("majom")));                         // nulla majom egy {1} ketto {2} harom {3} bla
	
	// az ordog nem alszik...
	var mf2 = new packages.nls.MessageFormat(" {{a}{b}c}");
	
	var gonosz = {"a":1,"b":2,"c":3,"d":4, "{a}{b}c":666, "a}{b":999 };
	for (var i in gonosz) {
		alert(i);
	}
	
	alert("res:" + mf2.format(gonosz));                                                   //  { 1 2 c }
}
© 2003-2020 lithium.io7.org
Content on this site is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.