Last active
August 29, 2015 14:01
-
-
Save danielsokolowski/0954fc2a767f441720b9 to your computer and use it in GitHub Desktop.
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
"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; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dimitarchristof - thank you for the feedback, the difference is about 6% faster good to know, I like returning the {...} for unmatched keys.