字符串的扩展_web

字符串的扩展

字符的unicode表示法
字符串的遍历器接口
直接输入U+2028和U+2029
json.stringify()的改造
模板字符串

模板编译
标签模板
模板字符串的限制

字符串的unicode表示法:
es6加强对unicode的支持,允许采用\uxxxx形式表示一个字符

"\u0061"
// "a"

这种表示法只限于码点在\u0000~\uFFFF之间的字符

"\uD842\uDFB7"
// "????"

"\u20BB7"
// " 7"
"\u{20BB7}"
// "????"

"\u{41}\u{42}\u{43}"
// "ABC"

let hello = 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' // true

字符串的遍历器接口

for...of循环遍历

for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"

最大的优点是可以识别大于0xFFFF的码点
```
let text = String.fromCodePoint(0x20BB7);

for (let i = 0; i < text.length; i++) {
console.log(text[i]);
}
// " "
// " "

for (let i of text) {
console.log(i);
}
// "????"


直接输入 u+2028 和 u+2029

'中' === '\u4e2d' // true


U+005C:反斜杠(reverse solidus)
U+000D:回车(carriage return)
U+2028:行分隔符(line separator)
U+2029:段分隔符(paragraph separator)
U+000A:换行符(line feed)

> 字符串里面不能直接包含反斜杠,一定要转义写成\\或者\u005c

服务器输出的 JSON 被JSON.parse解析,就有可能直接报错
const json = '"\u2028"';
JSON.parse(json); // 可能报错


const PS = eval("'\u2029'");


# JSON.stringify()
![file](https://graph.baidu.com/resource/212bd7741cd1386cadea701567353552.png)

JSON.stringify('\u{D834}') // "\u{D834}"


JSON.stringify('\u{D834}') // ""\uD834""
JSON.stringify('\uDF06\uD834') // ""\udf06\ud834""


模板字符串

$('#result').append(
'There are ' + basket.count + ' ' +
'items in your basket, ' +
'' + basket.onSale +
'
 are on sale!'
);

ES6 引入了模板字符串

$('#result').append(There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale!);


// 普通字符串
In JavaScript '\n' is a line-feed.

// 多行字符串
In JavaScript this is not legal.

console.log(string text line 1 string text line 2);

// 字符串中嵌入变量
let name = "Bob", time = "today";
Hello ${name}, how are you ${time}?


let greeting = \Yo` World!`;


$('#list').html(`

 

  •  
  • first

  • second


`);

 


$('#list').html(`

 

  •  
  • first

  • second


`.trim());

 


function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 传统写法为
// 'User '
// + user.name
// + ' is not authorized to do '
// + action
// + '.'
User ${user.name} is not authorized to do ${action}.);
}
}


let x = 1;
let y = 2;

${x} + ${y} = ${x + y}
// "1 + 2 = 3"

${x} + ${y * 2} = ${x + y * 2}
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
${obj.x + obj.y}
// "3"


function fn() {
return "Hello World";
}

foo ${fn()} bar
// foo Hello World bar


// 变量place没有声明
let msg = Hello, ${place};
// 报错

![file](https://graph.baidu.com/resource/2121ac3731566384ef4f801567355817.png)

const tmpl = addrs => <table> ${addrs.map(addr =>
${addr.first}
${addr.last}
).join('')} </table>;


const data = [
{ first: '', last: 'Bond' },
{ first: 'Lars', last: '' },
];

console.log(tmpl(data));
//


//
// 
// 
//
// 
// 
//
//

 
Bond
Lars
 

 

![file](https://graph.baidu.com/resource/212d5efabf80a491230e801567356140.png)
![file](https://graph.baidu.com/resource/212d87405aa276798588201567356236.png)

let evalExpr = /<%=(.+?)%>/g;
let expr = /<%([\s\S]+?)%>/g;

template = template
.replace(evalExpr, '); \n echo( $1 ); \n echo(')
.replace(expr, '); \n $1 \n echo(');

template = 'echo(' + template + ');';


let script =
`(function parse(data){
let output = "";

function echo(html){
output += html;
}

${ template }

return output;
})`;

return script;

![file](https://graph.baidu.com/resource/212f1d46875abb2b3fa5d01567356539.png)

alert123
// 等同于
alert(123)


let a = 5;
let b = 10;

function tag(s, v1, v2) {
console.log(s[0]);
console.log(s[1]);
console.log(s[2]);
console.log(v1);
console.log(v2);

return "OK";
}

tagHello ${ a + b } world ${ a * b};
// "Hello "
// " world "
// ""
// 15
// 50
// "OK"

![file](https://graph.baidu.com/resource/212cc3289da92f2c05b8801567356808.png)

![file](https://graph.baidu.com/resource/212b9eef3cefa81f7e2f401567356818.png)

![file](https://graph.baidu.com/resource/2124b62a53f3a5b1ee96b01567356839.png)

![file](https://graph.baidu.com/resource/212e0edaacc118bd541d101567356874.png)

![file](https://graph.baidu.com/resource/212031f2878a22144f64201567356956.png)

![file](https://graph.baidu.com/resource/212d69e1e9ebdd611582901567356973.png)

模板字符串默认会将字符串转义,导致无法嵌入其他语言。

function latex(strings) {
// ...
}

let document = latex`
\newcommand{\fun}{\textbf{Fun!}} // 正常工作
\newcommand{\unicode}{\textbf{Unicode!}} // 报错
\newcommand{\xerxes}{\textbf{King!}} // 报错

Breve over the h goes \u{h}ere // 报错
`
```


作者:阮一峰

字符串的扩展_web_02