Skip to content

Instantly share code, notes, and snippets.

@jmgimeno
Created November 26, 2011 19:47
Show Gist options
  • Save jmgimeno/1396218 to your computer and use it in GitHub Desktop.
Save jmgimeno/1396218 to your computer and use it in GitHub Desktop.
Python-like interpolation for JavaScript
/**
* 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++];
});
}
@jmgimeno
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment