Created
December 5, 2013 21:12
-
-
Save EdgeCaseBerg/7813980 to your computer and use it in GitHub Desktop.
interpolation function for javascript. Converts strings like "{0}" to substituted values.
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 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