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

手写E6字符串模板 #103

Open
GGXXMM opened this issue May 2, 2021 · 0 comments
Open

手写E6字符串模板 #103

GGXXMM opened this issue May 2, 2021 · 0 comments
Labels
es6 es6 knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented May 2, 2021

function render(template, data) {
  const reg = /\$\{(\w+)\}/;
  if(reg.test(template)){
    const name = reg.exec(template)[1];
    template = template.replace(reg, data[name]);
    return render(template, data);// 递归查找字符串模板变量,并渲染
  }
  return template;// 如果没有字符串模板,直接返回
}

// Test
let template = '我是${name},年龄${age},性别${sex}';
let person = {
    name: '布兰',
    age: 12
}
render(template, person); // output:我是布兰,年龄12,性别undefined
@GGXXMM GGXXMM added the es6 es6 knowledge label Dec 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
es6 es6 knowledge
Projects
None yet
Development

No branches or pull requests

1 participant