Login

Python-like string interpolation in Javascript

Author:
phxx
Posted:
June 20, 2010
Language:
JavaScript
Version:
1.2
Score:
2 (after 2 ratings)

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.

 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. Django Collapsed Stacked Inlines by applecat 1 year, 10 months ago
  2. Django Collapsed Stacked Inlines by mkarajohn 3 years, 11 months ago
  3. Dynamically adding forms to a formset. OOP version. by halfnibble 9 years, 7 months ago
  4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 11 years, 8 months ago
  5. Django admin inline ordering - javascript only implementation by ojhilt 12 years ago

Comments

brokenseal (on June 21, 2010):

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

#

Please login first before commenting.