Login

Python-like string interpolation in Javascript

Author:
phxx
Posted:
June 20, 2010
Language:
JavaScript
Version:
1.2
Tags:
template javascript string interpolation replace
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. Base64Field: base64 encoding field for storing binary data in Django TextFields by bikeshedder 5 years, 7 months ago
  2. Verbose template filter : avoid too many if by romain-hardouin 6 years, 9 months ago
  3. testdata tag for templates by showell 5 years, 11 months ago
  4. django_template decorator by fredd4 7 years, 1 month ago
  5. render_markup filter, specify the markup filter as a string by exogen 7 years, 11 months ago

Comments

brokenseal (on June 21, 2010):

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

#

Please login first before commenting.