Python-like string interpolation in Javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Provides python-like string interpolation.
 * It supports value interpolation either by keys of a dictionary or
 * by index of an array.
 *
 * Examples::
 *
 *      interpolate("Hello %s.", ["World"]) == "Hello World."
 *      interpolate("Hello %(name)s.", {name: "World"}) == "Hello World."
 *      interpolate("Hello %%.", {name: "World"}) == "Hello %."
 *
 * This version doesn't do any type checks and doesn't provide
 * formating support.
 */
function interpolate(s, args) {
    var i = 0;
    return s.replace(/%(?:\(([^)]+)\))?([%diouxXeEfFgGcrs])/g, function (match, v, t) {
        if (t == "%") return "%";
        return args[v || i++];
    });
}

More like this

  1. Base64Field: base64 encoding field for storing binary data in Django TextFields by bikeshedder 4 years, 8 months ago
  2. Verbose template filter : avoid too many if by Romain Hardouin 5 years, 10 months ago
  3. testdata tag for templates by showell 4 years, 11 months ago
  4. django_template decorator by fredd4 6 years, 2 months ago
  5. render_markup filter, specify the markup filter as a string by exogen 7 years ago

Comments

brokenseal (on June 21, 2010):

Isn't this supposed to be a Django snippets site?

#

(Forgotten your password?)