Last active
August 23, 2018 05:03
-
-
Save mirinzhang/4474672af971a815b77a881ccaf7059a to your computer and use it in GitHub Desktop.
简化版模板字符串替换函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 简化版模板字符串替换函数 | |
* @param {string} str - 替换目标 | |
* @param {object} replacer - 替换值集合 | |
* @param {string} prefix - 替换字符左边界 | |
* @param {string} suffix - 替换字符右边界 | |
*/ | |
const templateReplacer = ( | |
str = '', | |
replacer = {}, | |
prefix = '{{', | |
suffix = '}}' | |
) => { | |
// 构建替换字符正则表达式 | |
const reg = new RegExp( | |
Object.keys(replacer) | |
.map(item => `${prefix}${item}${suffix}`) | |
.join('|'), | |
'gi' | |
); | |
return str.replace(reg, matched => { | |
// 删除模板字符串中的边界符,以便查找替换值 | |
const resetReg = new RegExp(`${prefix}|${suffix}`, 'ig'), | |
key = matched.replace(resetReg, ''); | |
return replacer[key]; | |
}); | |
}; | |
// 一行实现 | |
function render(template, data) { | |
return template.replace(new RegExp('{{(.*?)}}', 'g'), (match, key) => data[key.trim()] || match); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment