Interview icon indicating copy to clipboard operation
Interview copied to clipboard

Day402: 实现一个render(str,parameter)方法,将str中的占位符用parameter填充?(腾讯)

Open qappleh opened this issue 4 years ago • 1 comments

测试用例:
const str = "下周一{{people1}}和{{people2}}去游泳"
render(str,{
	people1:'小明',
	people2:'小红'
})

qappleh avatar Sep 22 '21 03:09 qappleh

最简单的方法就是 string.replaceAll()了吧

const stringReplace = (template: string, obj: { [k: string]: string }) => {
    const keys = Object.keys(obj)
    keys.forEach(k => {
        template = template.replaceAll(`{{${k}}}`, obj[k])
    })
    return template
}

也可以考虑用template来做

const stringReplace2 = (template: string, obj: { [k: string]: string }) => {
    return eval('`' +  template.replaceAll("{{", "${obj['").replaceAll("}}", "']}") + '`')
}

需要考虑的一点就是parameter会不会有一些奇怪的格式和符号, 最基本的应该没问题。 性能上好像是template literal会快一点。

square-li avatar Sep 25 '21 20:09 square-li