Created
November 7, 2014 04:43
-
-
Save jmcorpdev/4a481c67e143066a0d34 to your computer and use it in GitHub Desktop.
Substitute function with deep object access
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
function substitute(string, object, regexp) { | |
return string.replace(regexp || (/\\?\{([^{}]+)\}/g), function (match, name) { | |
if (match.charAt(0) == '\\') return match.slice(1); | |
name = name.split('.'); | |
var tmpObj = object; | |
while(name.length) { | |
tmpObj = tmpObj[name.splice(0,1)[0]]; | |
} | |
return (tmpObj != null) ? tmpObj : ''; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment