首页 > 代码库 > [ES6] 11. String Templates

[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}, Iam    IN    ${place}CITY`;console.log(greeting);/**    Hello, Iam    IN    New YorkCITY*/

 

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

 

[ES6] 11. String Templates