Preface:

ES6 (ES2015) introduces a number of new features to JavaScript, including a new feature related to string handling, template literals, which provide multi-line strings, string templates, and I believe many people already use them. The basic use of string templates is simple, so here’s a simple way to implement a string template using regular expressions.

String template

  • Grammar:I am {{name}}, occupation {{job}}, salary {{salary}}, will automatically read the current variables name, job, salary values and fill in.
  • It’s pretty handy, eliminating the tedious and error-prone process of concatenating strings, especially in DOM manipulation innerHTML.

Open to

The implementation replaces the placeholders in the string ‘I am {{name}}, occupation {{job}}, salary {{salary}}’ with variables.

Handwritten code:

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; 
}
Copy the code
  1. Define a template string regular /\{\{(\w+)\}\}/ to match the contents of the string {{}}, and then determine if there is a string template in the template by using if.

  2. If so, find the first template string field in the template, render it, replace it with the corresponding value, and return the rendered structure recursively via the render function.

  3. If not, the template string is returned.

Testing:

Let the template = 'I am {{name}}, {{job}}, {{salary}}' wages; Let person = {name: 'abba ', job:' abba ', salary:30000}; console.log(render(template, person)); // MY name is Abba, and my salary is 30000Copy the code

Results:

You have succeeded in implementing a simple string template through regular expressions.

conclusion

A little bit better every day……