之前写过一篇分享 配置文件中动态值的替换 ,最近在使用的时候发现有局限:参数数组中各个参数的顺序必须牢记,否则在替换的时候就弄乱了。
针对这个缺点,我做了一些改进:参数不用数组,改用对象。具体的实现比如,配置的模板为:"hello {name} world",那么参数就为:{ name: '张三' },最后替换的结果为:"hello 张三 world"。
这种方式好像也比较常见,比如 Vue 的国际化文件就可以配置动态参数,使用的方式就类似这种。
下面是具体的实现,感兴趣的读者可以一起交流:
/**
* 用指定参数替换占位符。比如 template: "hello {name} world", obj: { name: '张三' },则返回值为 "hello 张三 world"。
* @param { string | object } template - 带有占位符的模板。
* @param { object } obj - 参数对象
* @returns { string | object } 替换后的模板。
*/
function fillParams(template, obj) {
let temp = template
if (!isString(template)) {
temp = JSON.stringify(template)
}
const result = temp.replace(/\{([ \w]+)\}/g, (match, $0) => obj[$0.trim()])
if (isString(template)) {
return result
}
return JSON.parse(result)
}
function isString(param) {
return typeof param === 'string'
}