例一:

    1. function render(template, data) {
    2. const reg = /\{\{(\w+)\}\}/
    3. if (reg.test(template)) {
    4. const name = reg.exec(template)[1]
    5. template = template.replace(reg, data[name])
    6. return render(template, data)
    7. }
    8. return template
    9. }
    10. let template = '我是:{{name}},年龄:{{age}},性别:{{sex}}';
    11. let person = {
    12. name: 'xiaoming',
    13. age: 12,
    14. sex: '女'
    15. }
    16. console.log(render(template, person))
    17. // ==============================================
    18. // 写法二
    19. function render(template, data) {
    20. const reg = /\{\{(\w+)\}\}/g
    21. let str = template.replace(reg, (match, key) => data[key])
    22. return str
    23. }

    例二:

    1. const year = '2021';
    2. const month = '10';
    3. const day = '01';
    4. let template = '${year}-${month}-${day}';
    5. let context = { year, month, day };
    6. const str = render(template)(context);
    7. console.log(str) // 2021-10-01
    8. function render(template) {
    9. return function(context) {
    10. return template.replace(/\$\{(.*?)\}/g, (match, key) => context[key]);
    11. }
    12. }