字符串的扩展

字符串的扩展

字符的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

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

模板字符串

$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> 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(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);
$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`.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

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>

file
file

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

alert`123`
// 等同于
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";
}

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

file

file

file

file

file

file

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

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 // 报错
`

学习来源
作者:阮一峰
https://es6.ruanyifeng.com/#docs/string

若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理。


请点赞!因为你们的赞同/鼓励是我写作的最大动力!

欢迎关注达叔小生的简书!

这是一个有质量,有态度的博客

博客

posted @ 2019-09-02 00:58  达达前端  阅读(552)  评论(0编辑  收藏  举报