1.字符的unicode表示法 :將碼點放入大括號,正確解讀字符。
"\u{20BB7}"
// "𠮷"
"\u{41}\u{42}\u{43}"
// "ABC"
let hello = 123;
hell\u{6F} // 123
'\u{1F680}' === '\uD83D\uDE80'
// true
6中方法表示一個字符:
'\z' === 'z' // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true
2.字符串的遍歷器接口
let text = String.fromCodePoint(0x20BB7);
for (let i of text) {
console.log(i);
}
// "𠮷"
3.JSON。stringify()的改造
如果遇到0xD800
到0xDFFF
之間的單個碼點,或者不存在的配對形式,它會返回轉義字符串。
JSON.stringify('\u{D834}') // ""\\uD834""
JSON.stringify('\uDF06\uD834') // ""\\udf06\\ud834""
4.模板字符串:用反引號(`)標識。
// 普通字符串
`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!`;
使用反引號,所有模板字符串的空格和換行,都是會被保留的,如果不需要,則trim方法消除。
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`.trim());
模板字符串中嵌入變量,需要將變量名寫在${}中。
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
大括號內部是字符串,則原樣輸出。
`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: '<Jane>', last: 'Bond' },
{ first: 'Lars', last: '<Croft>' },
];
console.log(tmpl(data));
// <table>
//
// <tr><td><Jane></td></tr>
// <tr><td>Bond</td></tr>
//
// <tr><td>Lars</td></tr>
// <tr><td><Croft></td></tr>
//
// </table>
也可以寫成函數:
let func = (name) => `Hello ${name}!`;
func('Jack') // "Hello Jack!"
5.模板編譯(沒怎麼看明白。。。)
模板編譯函數:
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;
}
正式用法:
let parse = eval(compile(template));
div.innerHTML = parse({ supplies: [ "broom", "mop", "cleaner" ] });
// <ul>
// <li>broom</li>
// <li>mop</li>
// <li>cleaner</li>
// </ul>
6.標籤模板 : 函數調用的一種特殊形式。
“標籤”指的是函數,緊跟在後面的模板字符串就是它的參數;如果模板字符裏面有變量,需要先將模板字符串先處理成多個參數,在調用函數。
let a = 5;
let b = 10;
tag`Hello ${ a + b } world ${ a * b }`;
// 等同於
tag(['Hello ', ' world ', ''], 15, 50);
tag函數:第一個參數是一個數組(沒有變量替換的部分)
function tag(stringArr, value1 ,value2) {
//....
}
等同於
function tag(stringArr , ...values ) {
//...
}
舉例:
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"
“標籤模板”:
1.過濾HTML字符串,放置用戶輸入惡意內容。
let sender = '<script>alert("abc")</script>'; // 惡意代碼
let message = SaferHTML`<p>${sender} has sent you a message.</p>`;
message
// <p><script>alert("abc")</script> has sent you a message.</p>
2.多語言轉換(國際化處理)。
i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`
// "歡迎訪問xxx,您是第xxxx位訪問者!"
模板處理函數的第一個參數(模板字符串數組),還有一個raw屬性。
console.log`123`
// ["123", raw: Array[1]]
//保存的是轉以後的原字符串。
tag`First line\nSecond line`
function tag(strings) {
console.log(strings.raw[0]);
// strings.raw[0] 爲 "First line\\nSecond line"
// 打印輸出 "First line\nSecond line"
}
//strings.raw數組會將 \n 視爲 \\ 和 n 兩個字符,而不是換行符
7.模板字符串的限制:模板字符串默認會將字符串轉義
function tag(strs) {
strs[0] === undefined
strs.raw[0] === "\\unicode and \\u{55}";
}
tag`\unicode and \u{55}`
//第一個字符設置爲undefined,但是raw屬性依然可以得到原始字符串