Skip to content

Instantly share code, notes, and snippets.

@danielsokolowski
Last active August 29, 2015 14:01
Show Gist options
  • Save danielsokolowski/0954fc2a767f441720b9 to your computer and use it in GitHub Desktop.
Save danielsokolowski/0954fc2a767f441720b9 to your computer and use it in GitHub Desktop.
"use strict";
/*
* JQuery Substitute method allows for simple templating using JS Object dot notation.
* Contribute link: https://gist.github.com/danielsokolowski/0954fc2a767f441720b9
*
* @param strTemplate - string contain the replacement tokens
* @param objData - an Object represetnting your replacmenet values
*
* Example:
* var strTemplate = 'Hello {user.name}'
* var strDatra = {'user': 'Daniel Sokolowski'}
* alert($.substitute(strTemplate, objData)); // outputs 'Hello Daniel Sokolowski'
*
*/
$.substitute = function(strTemplate, objData) {
return strTemplate.replace(/\\?\{([^{}]+)\}/g, function(match, subMatch1) {
try {
if (match.charAt(0) == '\\')
return match.slice(1);
if (objData[subMatch1] != null)
return objData[subMatch1];
var keys = subMatch1.split(".");
var value = objData[keys.shift()]; // return first element and update the original array
while (keys.length !== 0) { // keep returning properties
value = value[keys.shift()]
}
return value != undefined ? value : match;
} catch (err) { // return any errors as a string
return match;
}
});
};
@danielsokolowski
Copy link
Author

@dimitarchristof - thank you for the feedback, the difference is about 6% faster good to know, I like returning the {...} for unmatched keys.

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