[ES6] 11. String Templates

ECMAscript 6 lets us use string templates to gain a lot more control over strings in JavaScript.

var salutation = "Hello";
var place = "New York";
var greeting =`
    ${salutation}, I
am    IN

    ${place}

CITY
`;

console.log(greeting);

/**

    Hello, I
am    IN

    New York

CITY

*/

 

you can do expressions:

var x = 1;
var y = 2;

var sum = `${x} + ${y} = ${ x + y }`;
console.log(sum);  // 1 + 2 = 3

 

basic introduction to tagging these string templates:

var message = `It's ${new Date().getHours()}, I'm studying`;
console.log(message);  // It's 13, I'm studying

 

Now make those string as variable:

<!DOCTYPE html>
<html>
  <head>
    <script data-require="traceur@*" data-semver="0.0.0-20140302" src="https://traceur-compiler.googlecode.com/git/bin/traceur.js"></script>
    <script>
     traceur.options.experimental = true;
    </script>
    <script data-require="traceur@*" data-semver="0.0.0-20140302" src="https://traceur-compiler.googlecode.com/git/src/bootstrap.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
      <script type="module">
        function tag(strings, ...values){
            if(values[0] < 20){
                values[1] = "awake";
            }
            
            return `${strings[0]}${values[0]}${strings[1]}${values[1]}`;
        }
        
        var message = tag `It's ${new Date().getHours()}, I'am ${""}`;
        console.log(message);
      </script>
  </body>
</html>

 

posted @ 2014-11-22 19:19  Zhentiw  阅读(220)  评论(0编辑  收藏  举报