ECMAScript 6 入門教程—字符串的擴展

\uxxxx形式表示一個字符,其中xxxx表示字符的 Unicode 碼點。"\u0061"
// "a"
\u0000~\uFFFF之間的字符。超出這個范圍的字符,必須用兩個雙字節(jié)的形式表示。"\uD842\uDFB7"
// "?"
"\u20BB7"
// " 7"
\u后面跟上超過0xFFFF的數(shù)值(比如\u20BB7),JavaScript 會理解成\u20BB+7。由于\u20BB是一個不可打印字符,所以只會顯示一個空格,后面跟著一個7。"\u{20BB7}"
// "?"
"\u{41}\u{42}\u{43}"
// "ABC"
let hello = 123;
hell\u{6F} // 123
'\u{1F680}' === '\uD83D\uDE80'
// true
'\z' === 'z' // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true
2、字符串的遍歷器接口
for...of循環(huán)遍歷。for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"
0xFFFF的碼點,傳統(tǒng)的for循環(huán)無法識別這樣的碼點。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);
}
// "?"
text只有一個字符,但是for循環(huán)會認為它包含兩個字符(都不可打印),而for...of循環(huán)會正確識別出這一個字符。3、直接輸入 U+2028 和 U+2029
\u4e2d,兩者是等價的。'中' === '\u4e2d' // true
U+005C:反斜杠(reverse solidus) U+000D:回車(carriage return) U+2028:行分隔符(line separator) U+2029:段分隔符(paragraph separator) U+000A:換行符(line feed)
\\或者\u005c。JSON.parse解析,就有可能直接報錯。const json = '"\u2028"';
JSON.parse(json); // 可能報錯
const PS = eval("'\u2029'");
4、JSON.stringify() 的改造
JSON.stringify()方法有可能返回不符合 UTF-8 標準的字符串。0xD800到0xDFFF之間的碼點,不能單獨使用,必須配對使用。比如,\uD834\uDF06是兩個碼點,但是必須放在一起配對使用,代表字符?。這是為了表示碼點大于0xFFFF的字符的一種變通方法。單獨使用\uD834和\uDFO6這兩個碼點是不合法的,或者顛倒順序也不行,因為\uDF06\uD834并沒有對應的字符。JSON.stringify()的問題在于,它可能返回0xD800到0xDFFF之間的單個碼點。JSON.stringify('\u{D834}') // "\u{D834}"
JSON.stringify()的行為。如果遇到0xD800到0xDFFF之間的單個碼點,或者不存在的配對形式,它會返回轉義字符串,留給應用自己決定下一步的處理。JSON.stringify('\u{D834}') // ""\\uD834""
JSON.stringify('\uDF06\uD834') // ""\\udf06\\ud834""
5、模板字符串
$('#result').append(
'There are ' + basket.count + ' ' +
'items in your basket, ' +
'' + basket.onSale +
' are on sale!'
);
$('#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(`
<ul>
<li>firstli>
<li>secondli>
ul>
`);
標簽前面會有一個換行。如果你不想要這個換行,可以使用trim方法消除它。$('#list').html(`
<ul>
<li>firstli>
<li>secondli>
ul>
`.trim());
${}之中。function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 傳統(tǒng)寫法為
// '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
toString方法。// 變量place沒有聲明
let msg = `Hello, ${place}`;
// 報錯
`Hello ${'World'}`
// "Hello World"
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}td>tr>
<tr><td>${addr.last}td>tr>
`).join('')}
table>
`;
const data = [
{ first: '', last: 'Bond' },
{ first: 'Lars', last: '' },
];
console.log(tmpl(data));
//
//
//
//Bond
//
//Lars
//
//
//
let func = (name) => `Hello ${name}!`;
func('Jack') // "Hello Jack!"
6、實例:模板編譯
let template = `
<ul>
<% for(let i=0; i < data.supplies.length; i++) { %>
<li><%= data.supplies[i] %>li>
<% } %>
ul>
`;
<%...%>放置 JavaScript 代碼,使用<%= ... %>輸出 JavaScript 表達式。echo('');
for(let i=0; i < data.supplies.length; i++) {
echo('');
echo(data.supplies[i]);
echo('');
};
echo('');
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 + '`);';
template封裝在一個函數(shù)里面返回,就可以了。let script =
`(function parse(data){
let output = "";
function echo(html){
output += html;
}
${ template }
return output;
})`;
return script;
compile。function compile(template){
const evalExpr = /<%=(.+?)%>/g;
const 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;
}
compile函數(shù)的用法如下。let parse = eval(compile(template));
div.innerHTML = parse({ supplies: [ "broom", "mop", "cleaner" ] });
//
//- broom
//- mop
//- cleaner
//
7、標簽模板
alert`123`
// 等同于
alert(123)
let a = 5;
let b = 10;
tag`Hello ${ a + b } world ${ a * b }`;
// 等同于
tag(['Hello ', ' world ', ''], 15, 50);
tag,它是一個函數(shù)。整個表達式的返回值,就是tag函數(shù)處理模板字符串后的返回值。tag依次會接收到多個參數(shù)。function tag(stringArr, value1, value2){
// ...
}
// 等同于
function tag(stringArr, ...values){
// ...
}
tag函數(shù)的第一個參數(shù)是一個數(shù)組,該數(shù)組的成員是模板字符串中那些沒有變量替換的部分,也就是說,變量替換只發(fā)生在數(shù)組的第一個成員與第二個成員之間、第二個成員與第三個成員之間,以此類推。tag函數(shù)的其他參數(shù),都是模板字符串各個變量被替換后的值。由于本例中,模板字符串含有兩個變量,因此tag會接受到value1和value2兩個參數(shù)。tag函數(shù)所有參數(shù)的實際值如下。第一個參數(shù): ['Hello ', ' world ', '']第二個參數(shù): 15 第三個參數(shù):50
tag函數(shù)實際上以下面的形式調用。tag(['Hello ', ' world ', ''], 15, 50)
tag函數(shù)的代碼。下面是tag函數(shù)的一種寫法,以及運行結果。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";
}
tag`Hello ${ a + b } world ${ a * b}`;
// "Hello "
// " world "
// ""
// 15
// 50
// "OK"
let total = 30;
let msg = passthru`The total is ${total} (${total*1.05} with tax)`;
function passthru(literals) {
let result = '';
let i = 0;
while (i < literals.length) {
result += literals[i++];
if (i < arguments.length) {
result += arguments[i];
}
}
return result;
}
msg // "The total is 30 (31.5 with tax)"
passthru函數(shù)采用 rest 參數(shù)的寫法如下。function passthru(literals, ...values) {
let output = "";
let index;
for (index = 0; index < values.length; index++) {
output += literals[index] + values[index];
}
output += literals[index]
return output;
}
let message =
SaferHTML`<p>${sender} has sent you a message.p>`;
function SaferHTML(templateData) {
let s = templateData[0];
for (let i = 1; i < arguments.length; i++) {
let arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/&/g, "&")
.replace(/, "<")
.replace(/>/g, ">");
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
sender變量往往是用戶提供的,經過SaferHTML函數(shù)處理,里面的特殊字符都會被轉義。let sender = ''; // 惡意代碼
let message = SaferHTML`<p>${sender} has sent you a message.p>`;
message
//has sent you a message.
i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`
// "歡迎訪問xxx,您是第xxxx位訪問者!"
// 下面的hashTemplate函數(shù)
// 是一個自定義的模板處理函數(shù)
let libraryHtml = hashTemplate`
<ul>
#for book in ${myBooks}
<li><i>#{book.title}i> by #{book.author}li>
#end
ul>
`;
jsx`
<div>
<input
ref='input'
onChange='${this.handleChange}'
defaultValue='${this.state.value}' />
${this.state.value}
div>
`
jsx函數(shù),將一個 DOM 字符串轉為 React 對象。你可以在 GitHub 找到jsx函數(shù)的具體實現(xiàn)。java函數(shù),在 JavaScript 代碼之中運行 Java 代碼。java`
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
`
HelloWorldApp.main();
raw屬性。console.log`123`
// ["123", raw: Array[1]]
console.log接受的參數(shù),實際上是一個數(shù)組。該數(shù)組有一個raw屬性,保存的是轉義后的原字符串。tag`First line\nSecond line`
function tag(strings) {
console.log(strings.raw[0]);
// strings.raw[0] 為 "First line\\nSecond line"
// 打印輸出 "First line\nSecond line"
}
tag函數(shù)的第一個參數(shù)strings,有一個raw屬性,也指向一個數(shù)組。該數(shù)組的成員與strings數(shù)組完全一致。比如,strings數(shù)組是["First line\nSecond line"],那么strings.raw數(shù)組就是["First line\\nSecond line"]。兩者唯一的區(qū)別,就是字符串里面的斜杠都被轉義了。比如,strings.raw 數(shù)組會將\n視為\\和n兩個字符,而不是換行符。這是為了方便取得轉義之前的原始模板而設計的。8、模板字符串的限制
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 // 報錯
`
document內嵌的模板字符串,對于 LaTEX 語言來說完全是合法的,但是 JavaScript 引擎會報錯。原因就在于字符串的轉義。\u00FF和\u{42}當作 Unicode 字符進行轉義,所以\unicode解析時報錯;而\x56會被當作十六進制字符串轉義,所以\xerxes會報錯。也就是說,\u和\x在 LaTEX 里面有特殊含義,但是 JavaScript 將它們轉義了。undefined,而不是報錯,并且從raw屬性上面可以得到原始字符串。function tag(strs) {
strs[0] === undefined
strs.raw[0] === "\\unicode and \\u{55}";
}
tag`\unicode and \u{55}`
undefined,但是raw屬性依然可以得到原始字符串,因此tag函數(shù)還是可以對原字符串進行處理。let bad = `bad escape sequence: \unicode`; // 報

評論
圖片
表情
