Last active
February 21, 2024 11:50
-
-
Save padolsey/6008842 to your computer and use it in GitHub Desktop.
Dead simple straight-up performant interpolation
This file contains 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
/** | |
* Outputs a new function with interpolated object property values. | |
* Use like so: | |
* var fn = makeInterpolator('some/url/{param1}/{param2}'); | |
* fn({ param1: 123, param2: 456 }); // => 'some/url/123/456' | |
*/ | |
var makeInterpolator = (function() { | |
var rc = { | |
'\n': '\\n', '\"': '\\\"', | |
'\u2028': '\\u2028', '\u2029': '\\u2029' | |
}; | |
return function makeInterpolator(str) { | |
return new Function( | |
'o', | |
'return "' + ( | |
str | |
.replace(/["\n\r\u2028\u2029]/g, function($0) { | |
return rc[$0]; | |
}) | |
.replace(/\{([\s\S]+?)\}/g, '" + o["$1"] + "') | |
) + '";' | |
); | |
}; | |
}()); | |
var url = makeInterpolator('http://something.com/{param}/{foo}?x={n}'); | |
url({ | |
param: '123', | |
foo: '456', | |
n: 789 | |
}); |
Only special-casing \n
and \r
is not enough. Having \u2028
or \u2029
in the input string still throws an error. Just replace them with their (double-)escaped equivalents and you’ll be fine.
@mathiasbynens: cool, thanks! -- just edited it.
@padolsey I got what you were going for after I read your blog post
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@padolsey FWIW, @rodneyrehm’s URI.js also supports it: http://medialize.github.io/URI.js/uri-template.html