Javascript format strings
Posted: Last updated:Python has been my favorite language for a while but since I started making Mozilla Extensions I've started to like Javascript a lot too. One thing I miss from Python though are the format strings. In Python you can always create a string like this:
s = '%s is a %s' % ('John', 'Moron')
Since Javascript is a very flexible language and allows you to alter its built in types I decided to try to create something similar for it. Here's what I came up with:
String.prototype.$ = function() {
s = this;
if (arguments.length == 1 && arguments[0].constructor == Object) {
for (var key in arguments[0]) {
s = s.replace(new RegExp("\$" + key, "g"), arguments[0][key]);
}
} else {
for (var i = 0; i < arguments.length; i++) {
s = s.replace(new RegExp("\$" + (i+1), "g"), arguments[i]);
}
}
return s;
};
The function works in two ways.
-
You can send in 1-n parameters and then $1 – $n in the string will be replaced by the parameters values. Example
var undef; //Undefined value var s = 'My name is $1 and I am $2 years old. This is a null variable: $3, this one is undefined: $4' .$ ('Einar', 27, null, undef); alert(s);
-
You can send in 1 parameter that's a javascript object and then $keyname in the string will be replaced by the value for "keyname" in the javascript object. Example
var d; //Undefined value var dict = { name : 'Einar', age : 27, nullvar : null, undef : d }; var s = 'My name is $name and I am $age years old. This is a null variable: $nullvar, this one is undefined: $undef' .$ (dict); alert(s);
This works fine in Mozilla Firefox and Internet Explorer 7, I haven't tested it in other browsers. I know the $ is used for document.getElementById in prototype and maybe other js libraries but I thought it was the best choice here too, I don't think it's confusing to use it for these two things. In case the syntax highlighting stuff screwed up the code on the page you can also download it here.