一.ES6模板字符串 传统定义字符串的方式是: const str='hello es2015,this is a string' ES6新增了一种定义字符串的方式用反引号进行标识 const str=`hello es2015, this is a string` 传统的字符串如果想换行的话需要如果加\n,而模板字符串的话可以直接换行 const name='tom' const msg=`hey,${name}` const mfg=`hey,${Math.ramdom()}` 模板字符串内
首先,模板字符串和标签模板是两个东西. 标签模板不是模板,而是函数调用的一种特殊形式.“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数. 但是,如果模板字符串中有变量,就不再是简单的调用了,而是要将模板字符串先处理成多个参数,再调用函数.(ES6标准入门-阮一峰 4.12标签模板) 由此引出此文,先上代码: var a = 5; var b = 10; tag`Hello ${ a + b } world ${ a * b }`; //等同于 tag(['Hello ', ' wor
1)直接使用变量 // before var str = 'test'; console.log(str + "123"); // now var str = 'test'; console.log(`${str}123`); 备注:如需使用字符$或{,请使用`\$`或`\{` 2)多行书写 // before document.write( '<div>' + '<span>test<span>' + '</div>') // now
模板字面量 是允许嵌入表达式的字符串字面量. 你可以使用多行字符串和字符串插值功能.它们在ES2015规范的先前版本中被称为“模板字符串”. 语法 `string text``string text line 1 string text line 2``string text ${expression} string text`tag `string text ${expression} string text` 描述 模板字符串使用反引号 () 来代替普通字符串中的用双引号和单引号.模板
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification. http://es6.ruanyi