码迷,mamicode.com
首页 > 其他好文 > 详细

[ES6] 11. String Templates

时间:2014-11-22 20:09:05      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

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:

function tagStr(strings, value1, value2) {
    console.log(strings);  // [ ‘It\‘s ‘, ‘, I\‘m studying‘ ]
    console.log(value1);  // 13
    console.log(value2);  // 13

    if(value1 < 10){
        value2 = "Sleeping";
    }else if(value1 >= 10 && value1 < 22){
        value2 = "Studying";
    }else{
        value2="dreaming";
    }

    return `${strings[0]}${value1}${strings[1]}${value2}`;
}

var eg = "CS";
var message = tagStr`It‘s ${new Date().getHours()},I‘m ${""}`;
console.log(message);  //It‘s 13,I‘m Studying

 

bubuko.com,布布扣

[ES6] 11. String Templates

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/Answer1215/p/4115528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!