首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。