Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
qappleh opened this issue Sep 22, 2021 · 1 comment

Comments

@qappleh
Copy link
Owner

qappleh commented Sep 22, 2021

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

最简单的方法就是 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会快一点。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants