simple string interpolation in javascript

11 March 2008 // javascript. stuff.

two-liner that adds perl/php style string interpolation to javascript

 

function f(str, obj) {
    var a = arguments, obj = obj || window || this;
    return str.replace(/(\\\$)|(\$\$)|\$([0-9])|\$(\w+)|\$\{(\w+)\}/g,
        function() {
            var q = arguments;
            return (q[1] || q[2]) ? '$' : q[3] ? a[q[3]] :
                q[4] ? obj[q[4]] : obj[q[5]];
    });
}

f(some_string) replaces ("interpolates") placeholders like $var or ${var} or $5 in the string. f can be called with one, two or more arguments. If only one argument is given (= the format string), $var placeholders are replaced with global variables or window properties:

s = f("position $screenX, $screenY");
alert(s);

With two arguments, the second should be an object and $var s are replaced with the corresponding properties of that object

img = {
    src: 'woo.gif',
    title: 'hello',
    width: 150
};
s = f("<img src='$src' title='$title' style='width:${width}px'>", img);
alert(s);

Numeric placeholders $1 , $2 etc. are replaced with the value of the n-th argument:

s = f("There are $1 monkeys on the $2", 100, 'tree');
alert(s);

You can mix numeric and symbolic placeholders:

format = { bg: "black", fg: "white" }
s = f("<p style='background:$bg;color:$fg'>$2</p> ", format, "hello");
alert(s);

\\$ or $$ escape the dollar sign:

s = f("$1 costs \\$2 and $2 costs $$5", "a beer", "a meal");
alert(s);
 
If you think this comment is spam or otherwise completely irrelevant here, feel free to hide it. The comment disappears immediately, though it is not deleted, so I have an option to "unhide" it later.

развратное порно видео :

comment6, <a href=" http://sanchezo... ">педики секс</a>, mbdq,

порно фото галереи секс с животными :

comment5, <a href=" http://sanchezo... ">фото секс жестокий изнасилования</a>, :[[[,

 

comment on this