3 回答

TA貢獻1875條經驗 獲得超3個贊
模板字符串是一種文字 - 這意味著,它們僅在編譯步驟中可用(包括由eval和朋友編譯,如另一個答案所示,該答案也警告不要使用它們)。
模板字符串的流式傳輸是一個 XY 問題。相反,考慮問題本身,您希望通過填充插槽來翻譯模板。您可以使用正則表達式來做到這一點,只要您沒有在插槽內進行計算(就像使用模板字符串那樣)。您還可能希望將局部變量更改為對象屬性,以便可以通過名稱以編程方式訪問它們,而無需eval.
const context = { name: "Tim" };
const textResponse = "Hi ${name}, how are you?";
const greetUserInHisLanguage =
textResponse.replace(/\${(.*?)}/g, (_, name) => context[name]);
console.log(greetUserInHisLanguage);
如果您需要更復雜的東西,請考慮使用現有的模板庫,如 Handlebars。

TA貢獻2051條經驗 獲得超10個贊
試試這個,你可以使用eval()
myFunction (language) {
const name = "Tim";
// call to the cms for translation
// returns "Hi ${name}, how are you?";
const textResponse = getTranslation(language);
// How to convert textResponse into a template string and fill in ${name}
// with "Tim"?
const greetUserInHisLanguage =eval('`'+textResponse+'`') // use eval()
return greetUserInHisLanguage;
}
工作小提琴-
function myFunction(language) {
const name = "Tim";
// call to the cms for translation
// returns "Hi ${name}, how are you?";
const textResponse = getTranslation(language);
// How to convert textResponse into a template string and fill in ${name}
// with "Tim"?
const greetUserInHisLanguage = eval('`'+textResponse+'`') // use template literals here
return greetUserInHisLanguage;
}
function getTranslation(language) {
return "Hi ${name}, how are you?"
}
console.log(myFunction("spanish"))
值得注意
不推薦使用 eval(),因為它容易受到注入攻擊
添加回答
舉報