I have this code, that can take a string and some variables and inject the variables into the string. This is needed in my app because the text often comes from a CMS and have to be editable. Sometimes the variable part of the string is colored or a different font so I was trying to make it so that i could wrap it in if necessary. But my react app posts everything as a string.
var VariableInjection = (stringToEdit, variablesToInject) => {
const matches = stringToEdit.match(/{[a-z][A-z]*}/g);
const strippedMatches = matches.map(m => m.replace('{', '')).map(m => m.replace('}', ''));
for (let i = 0; i < matches.length; i += 1) {
const replaceWith = variablesToInject[strippedMatches[i]];
if (typeof replaceWith === 'string' || typeof replaceWith === 'number') {
stringToEdit = stringToEdit.replace(matches[i], replaceWith);
} else {
stringToEdit = stringToEdit.replace(matches[i], `<span class="${replaceWith.class}">${replaceWith.value}</span>`);
}
}
return stringToEdit;
};
VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: 2})
gives:
'this is the 1 and this is the 2'
VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: { value:2, class:"test Class"})
gives:
'this is the 1 and this is the <span class="test Class">2</span>'