Created
November 26, 2011 19:47
-
-
Save jmgimeno/1396218 to your computer and use it in GitHub Desktop.
Python-like interpolation for JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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++]; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://djangosnippets.org/snippets/2074/