js replace word in a string with list of pair set - NaClYen/blog GitHub Wiki
使用情境
一個字串需要連續通過多組 replace keyword.
demo
// pair set
const replacePair = [
["{XXX}", filePrefix],
["\\`", "`"],
["\\$", "$"]
];
// use reduce to iterate pairs
const replaceFilePrefix = (template) => {
return replacePair.reduce((last, pair) => {
const [keyword, replcement] = pair;
return last.replace(keyword, replcement);
}, template);
};