字符串的扩展字符串的Unicode表示法字符串的遍历接口直接输入U+2028和U+2029json.stringify()转换模板字符串模板编译标签模板字符串的限制字符字符串unicode表示法:es6加强对unicode的支持,允许使用uxxxx来表示一个字符"\u0061"//"a"这种表示法仅限于代码点在u0000~uFFFF"\uD842\uDFB7"//"?""\u20BB7之间的字符"//"7""\u{20BB7}"//"?""\u{41}\u{42}\u{43}"//"ABC"lethello=123;hell\u{6F}//123'\u{1F680}'==='\uD83D\uDE80'//true花括号表示法相当于四字节UTF-16编码'\z'==='z'//true'\172'==='z'//true'\x7A'==='z'//true'\u007A'==='z'//true'\u{7A}'==='z'//truestringtraverserinterfacefor...oflooptraversalfor(letcodePointof'foo'){console.log(codePoint)}//"f"//"o"//"o"的最大优点是它可以识别大于0xFFFF的代码点lettext=String.fromCodePoint(0x20BB7);for(leti=0;我<文本.长度;i++){控制台。log(text[i]);}//""//""for(letioftext){console.log(i);}//"?"直接输入u+2028andu+2029'in'==='\u4e2d'//trueU+005C:reverseslash(反斜线)U+000D:carriagereturn(回车)U+2028:lineseparator(行分隔符)U+2029:段落分隔符(paragraphseparator)U+000A:换行符(linefeed)字符串不能直接包含反斜杠,必须转义写成\或u005c服务如果设备输出的JSON是用JSON.parse解析的,可能会直接报错constjson='"\u2028"';JSON.parse(json);//可能报错constPS=eval("'\u2029'");JSON.stringify()JSON.stringify('\u{D834}')//"\u{D834}"JSON.stringify('\u{D834}')//""\\uD834""JSON.stringify('\uDF06\uD834')//""\\udf06\\ud834""模板字符串$('#result').append('有'+basket.count+''+'你的购物篮里有商品,'+''+basket.onSale+'正在打折!');ES6引入了模板字符串$('#result').append(`您的购物车中有${basket.count}件商品,${basket.onSale}正在sale!`);//普通字符串`在JavaScript中'\n'是一个换行符。`//多行字符串`在JavaScript中这是不合法的。`console.log(`stringtextline1stringtextline2`);//字符串中的嵌入变量letname="Bob",time="today";`Hello${name},howareyou${time}?`letgreeting=`\`Yo\``;$('#list').html(`
`);$('#list').html(`
`.trim());functionauthorize(user,action){if(!user.hasPrivilege(action)){thrownewError(//传统写法为//'User'//+user.name//+'isnotauthorizedtodo'//+action//+'.'`User${user.name}isnotauthorizedtodo${动作}。`);}}letx=1;lety=2;`${x}+${y}=${x+y}`//"1+2=3"`${x}+${y*2}=${x+y*2}`//"1+4=5"让obj={x:1,y:2};`${obj.x+obj.y}`//"3"functionfn(){return"HelloWorld";}`foo${fn()}bar`//fooHelloWorldbar//变量place没有声音letmsg=`Hello,${place}`;//报错consttmpl=addrs=>`
${addrs.map(addr=>`${addr.first} |
${addr.last} |
`).join('')}
`;constdata=[{first:'
',last:'Bond'},{first:'Lars',最后:''},];console.log(tmpl(data));//让evalExpr=/<%=(.+?)%>/g;letexpr=/<%([\s\S]+?)%>/g;template=template.replace(evalExpr,'`);\n回显($1);\necho(`').replace(expr,'`);\n$1\necho(`');template='echo(`'+template+'`);';letscript=`(functionparse(data){letoutput="";functionecho(html){output+=html;}${template}returnoutput;})`;returnscript;alert`123`//等价于alert(123)leta=5;letb=10;functiontag(s,v1,v2){console.log(s[0]);控制台日志(s[1]);控制台日志(s[2]);控制台日志(v1);控制台日志(v2);return"OK";}tag`Hello${a+b}world${a*b}`;//"Hello"//"world"//""//15//50//"OK"模板字符串默认会对字符串进行转义,无法嵌入其他语言functionlatex(strings){//...}letdocument=latex`\newcommand{\fun}{\textbf{Fun!}}//工作正常\newcommand{\unicode}{\textbf{Unicode!}}//报错\newcommand{\xerxes}{\textbf{King!}}//报错Breveoverthehgoes\u{h}ere//报错`学习源作者:阮一峰https://es6.ruanyifeng.com/#d...如本账号内容有问题(例如:涉及版权或其他问题),请及时联系我们进行整改,我们会尽快处理。请喜欢它!因为您的认可/鼓励是我写作最大的动力!欢迎关注大叔小生简书!这是一个有品质有态度的博客