西寧網(wǎng)站設(shè)計公司seo外鏈平臺
要在js中想要替換替換模板中的${},可以使用字符串的replace()方法結(jié)合正則表達(dá)式或者函數(shù)來實現(xiàn)替換操作。
以下是兩種常見的替換方式: 使用正則表達(dá)式:
方法一:
const template = "Hello, ${name}! Today is ${day}.";
const data = {name: "John",day: "Monday"
};const result = template.replace(/\${(.*?)}/g, (match, key) => data[key]);
console.log(result); // 輸出: Hello, John! Today is Monday.
方法二:
const template = "Hello, ${name}! Today is ${day}.";
const data = {name: "John",day: "Monday"
};const result = template.replace(/\${(.*?)}/g, (match, key) => {return data.hasOwnProperty(key) ? data[key] : match;
});
console.log(result); // 輸出: Hello, John! Today is Monday.