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. Initially open collapsable fieldset class in admin by ralfzen 2 years, 8 months ago
  2. JavaScript implementation of Python xrange() builtin by fish2000 2 years, 5 months ago
  3. Client-side Django-style date & time string formatting by robbie 6 years, 2 months ago
  4. Repeat blocks with new context / simple Jinja-like macro system by miracle2k 5 years, 9 months ago
  5. Cacheable resources by jbrisbin 4 years, 9 months ago

Comments

brokenseal (on June 21, 2010):

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

#

(Forgotten your password?)