1
我有這段代碼,它可以接受一個字符串和一些變量並將這些變量注入到字符串中。這是我的應用程序所需要的,因爲文本通常來自CMS並且必須是可編輯的。有時,字符串的可變部分是彩色的或不同的字體,所以我試圖使它可以在必要時包裹它。但我的反應應用程序發佈一切爲一個字符串。我怎樣才能將一個跨度注入到一個字符串中,並將其打印在我的反應應用程序中作爲HTML
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})
給出:
'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"})
給出:
'this is the 1 and this is the <span class="test Class">2</span>'