ES6 Features Series: template Strings & Tagged template Strings

Source: Internet
Author: User
Tags control characters

1. Brief

ES6 (ECMAScript 6th edition) was released in July 2015, although the major browsers still do not fully support ES6, but we can on the backend through the node. js 0.12 and Io.js, and the front end through traceur or Babel such transpiler will ES6 grammar pre-translated into ES5 grammar, to advance excitement. Friends who only need to adapt to ie9+ are now more able to start ES6 without worrying about which JavaScript superset language to learn. (ES6 also known as ECMAScript 2015 or JAVASCRIPT.NEXT,ES4, some of the more aggressive features are called to implement in this release.) )

ES6 brings us a lot of surprises, such as class, module, export and import. However, in the study and application of the project, we need to pay attention to the following two points:

1. ES6 contains the syntax sugar and the language, the library bug fix, does not have the very big help to the engineering question;

2. Since Traceur and Babel cannot fully and efficiently polyfill all the features of ES6, we cannot enjoy the full range of ES6 features.

Recently took over a project of front-end transformation, is experimenting with a new technology stack (Riot+es6+glup+webpack), this series of articles will be used as theoretical + project practice notes for future review.

2. What is Template Strings?

Word, Template strings lets us reduce the amount of manual concatenation of strings.

2.1. Before ES6

//Sample 1: Single-line string concatenationvarOperand1 =1, Operand2=2.1varTPL1 = Operand1 +' + '+ Operand2 +'~='+ parseint (operand1+operand2)varTPL2 = [Operand1,' + ', Operand2,'~=', parseint (Operand1 + operand2)].join ("')
//Sample 2: Multi-line string concatenationvarName ='Fsjohnhuang', id=' Region'varTPL1 ='<div id= "'+ ID +'">'+'<a>'+ name +'</a>'+'</div>'varTPL2 ='<div id= "'+ ID +'">\<a>'+ name +'</a>  </div>'

2.2. Embracing ES6

 //  Sample 1: single-line string concatenation  var  operand1 = 1  , Operand2  = 2.1  var  tpl1 = ' ${operand1}+${operand2}~=${parseint (operand1+operand2 )}`
// Sample 2: Multi-line string concatenation var ' Fsjohnhuang '   ' Region ' var tpl1 = ' <div id= ' ${id}    ">  <a>${name}</a>  </div> '

If you know Coffeescript, then you will find ES6 's template strings how so familiar. The Template strings consists of two parts:

1. The template starter-- "' , called the accent/back quotation mark (grave accent), whose contents are recognized as a string template.

2. Expression placeholder-- ${<expression>} ,<expression> is a valid expression for JavaScript (such as name, 1==2, etc.), so ${< Expression>} is not a simple placeholder.

2.3. Cautions

1. ${<expression> You can access variables and functions that are accessible to the current scope, such as

var 1 (function () {  var2  (function (b) {    var//  The result is "1,2,undefined,5"  } (5)  )var3    4 // variable Hoist} does not occur because a let is used to declare C variables ())

2. ${<expression>} is a real-time calculation (real-time computing), with a function shell to enable lazy calculation (lazy evaluation)

// Real-time Computing var tpl = ' ${x},${y} 'var12//  "Undefined, Undefined "//  lazy evaluationvar tpl = CTX = ' ${ctx.x},${ctx.y} '  //  "1, 2"

3. Multiline Trap (pitfall of multiline), I'm used to writing HTML templates as follows

var ' <div>\        <span>${subtitle}</span>  </div>'  //  then the template engine resolves the TPL

Is it now possible to switch to template strings without concern?

var tpl = CTX = ' <div>    '//  direct call to the TPL function

the answer is no.

The reason is that the actual output of a multiline string, defined by a forward slash ( \ ), is a single line of string , but a true multiline string is defined by an inverse quotation mark ( ' ), and a newline character ( \ n ) to separate each row.

// define multiple rows of results by \ <div>    //  using anti-quotes to define multiple rows of results <div>\    n\    n<span>${ctx.subtitle}</span>  \ n</div>

So when we use jquery to produce DOM elements with an HTML template that is an anti-quote definition, we need to remove these control characters.

var ")

3. What is Tagged Template Strings?

From the above we understand that the template strings is calculated on an as-is basis, which means that the autonomy we have is limited. The tagged Template strings greatly enhanced our manipulative desires.

In fact, tagged template strings is essentially a template strings tokenize operation, thus refining our operational granularity. The lexical type is divided into string and expression placeholders for the results of the operation .

var 1 2 var ' hello${x}:${y+1} ' // results after the tokenize var tokens = ['hello'1':' 3 "'

The specific gameplay is as follows:

//Grammar<tagged function><template strings>/** Sample **//*define <tagged function> * @param {array.<domstring>} strings-String type tokens * @param {... any} vals-expression placeholder operation result Tokens * @returns {any}*/varTaggedfunc =(Strings, ... vals) {varRET = []   for(Let i =0, Len = strings.length; i < Len; ++i) Ret.push (Strings.raw[i], vals[i]||"')  returnret}//Define template Stringsvarx =1, y =2varret = Taggedfunc ' \thello${x}:${y+1} ' Console.log (ret)//Show "\thello1:3"Console.log (' \thello${x}:${y+1}`)//Show "Hello1:3"

The <tagged function> function has two entry parameters representing two classes of tokens respectively. {array.<domstring>} strings is a string of type tokens, and {... Any} Vals is the result of an expression placeholder operation tokens.

and note that: strings.length = = = Vals.length + 1

In addition, we see that the last two lines of code will find that the tabs in ' \thello${x}:${y+1} ' will work in the output, while the tagged function is output as normal characters. In fact, this is the result of using the token in the {Array.<domstring>}strings.raw Property operation Strings, that is, the Strings.raw property will escape the control to implement the output according to ordinary characters.

3.1. Built-in tagged Function--string.raw

The effect is the same as the above Taggedfunc, which is to output the control in the template strings by ordinary characters.

3.2. Cautions

1. The syntax of Tagge template strings is that the template strings is immediately behind the tagged function and cannot have spaces or tabs between them.

2. Vals is the actual value after the operation, and the shell is still required to delay the calculation.

3. @ruanyifeng teacher says you can customize the template language with process control through tagged function

// the following hashtemplate function // is a custom template-handling function var libraryhtml = hashtemplate '  <ul>    #for in  ${ MyBooks}      <li><i>#{book.title}</i> by #{book.author}</li>    #end  </ul>';

I think this usage is not advisable, Tagged function would have been according to their own rules of the template tokenize, and then we on this basis on the results of two tokenize, it is not as straightforward as the rules of their own definition to do lexical analysis more worry.

4. Conclusion

Template Strings and tagged template Strings can be babel by Traceur and Transpile, so we can now roll up and do it!

Respect the original, reproduced please specify from: http://www.cnblogs.com/fsjohnhuang/p/4601200.html fat son John ^_^

5. Thanks

http://es6.ruanyifeng.com/#docs/string

http://www.sitepoint.com/understanding-ecmascript-6-template-strings/

ES6 Features Series: template Strings & Tagged template Strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.