Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created December 5, 2013 21:12
Show Gist options
  • Select an option

  • Save EdgeCaseBerg/7813980 to your computer and use it in GitHub Desktop.

Select an option

Save EdgeCaseBerg/7813980 to your computer and use it in GitHub Desktop.
interpolation function for javascript. Converts strings like "{0}" to substituted values.
function interpolate(str){
/* Interpolate on {[0-9]+} */
if (arguments.length < 2)
return str;
/* Break string by it's interpolation parts */
var split = str.split(/\{([0-9]+)\}/gm);
var numex = /^\d+$/
for (var i = split.length - 1; i >= 0; i--) {
if(numex.test(split[i])){
var idx = parseInt(split[i]);
if(arguments.length > idx +1){
/* Within interpolation bounds */
split[i] = arguments[idx+1];
}
}
};
return split.join(" ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment