Created
April 26, 2015 16:28
-
-
Save lisaah/f8fd5654542b9b7dd919 to your computer and use it in GitHub Desktop.
Format a string by expanding values mapped with String values in a nested Object.
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
/** | |
* Expand a string using a supplied regex to denote the properties and a | |
* possibly nested object to supply the values. | |
* | |
* inputString - The string to be formatted. | |
* valuesObject - An Object holding either values stored as strings or other Objects | |
* nestSeparator - The marker used to indicated a nested property | |
* propRegex - Regex used to indicate the property in the inputString. Assumes the actual | |
* key value will be indicated by using (). | |
* | |
* Example: | |
* expand("A message from afar reads: \"[test.input] [test.input2][pun]\"", | |
* {test: {input: "Hello", input2: "World"}, pun: "!"}, | |
* ".", /\[(.*?)\]/g)); | |
* Output: | |
* A message from afar reads: "Hello World!" | |
*/ | |
function expand(inputString, valuesObject, nestSeparator, propRegex) { | |
function fetchValue(match, nestedProp) { | |
var propArray = nestedProp.split(nestSeparator), | |
value = valuesObject, | |
prop; | |
for (var i = 0; i < propArray.length; i++) { | |
prop = propArray[i]; | |
if (!value[prop]) { | |
// If property is false-y, supply value as empty string. | |
value = ""; | |
break; | |
} | |
value = value[prop]; | |
} | |
return value; | |
} | |
inputString = inputString.replace(propRegex, fetchValue); | |
return inputString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment