以下就是JavaScript6中字符串的四個新用法:
一、Unicode字符的新表示方法
Unicode字符通常是21個bit的,而普通的JavaScript字符(大部分)是16bit的,可以編碼成UTF-16。超過16bit的字符需要用2個常規字符表示。
比如,下面的的代碼將會輸出一個Unicode小火箭字符(‘/uD83D/uDE80'),你可以在瀏覽器的console里試一下:
  console.log('/uD83D/uDE80');在 ECMAScript 6 里,可以使用新的表示方法,更簡潔:
  console.log('/u{1F680}');二、多行字符串定義和模板字符串
模板字符串提供了三個有用的語法功能。
首先,模板字符串支持嵌入字符串變量:
  let first = 'Jane';  let last = 'Doe';  console.log(`Hello ${first} ${last}!`);    // Hello Jane Doe!第二,模板字符串支持直接定義多行字符串:
let multiLine = ` This is a string with multiple lines`;
	第三,如果你把字符串加上String.raw前綴,字符串將會保持原始狀況。反斜線(/)將不表示轉義,其它專業字符,比如 /n 也不會被轉義:
let raw = String.raw`Not a newline: /n`; console.log(raw === 'Not a newline: //n'); // true
三、循環遍歷字符串
	字符串可遍歷循環,你可以使用 for-of 循環字符串里的每個字符:
  for (let ch of 'abc') {    console.log(ch);  }  // Output:  // a  // b  // c而且,你可以使用拆分符 (...) 將字符串拆分成字符數組:
let chars = [...'abc']; // ['a', 'b', 'c']
四、字符串包含判斷和重復復制字符串
有三個新的方法能檢查一個字符串是否包含另外一個字符串:
  > 'hello'.startsWith('hell')  true  > 'hello'.endsWith('ello')  true  > 'hello'.includes('ell')  true這些方法有一個可選的第二個參數,指出搜索的起始位置:
  > 'hello'.startsWith('ello', 1)  true  > 'hello'.endsWith('hell', 4)  true    > 'hello'.includes('ell', 1)  true  > 'hello'.includes('ell', 2)  false	repeat()方法能重復復制字符串:
> 'doo '.repeat(3) 'doo doo doo '
總結
以上就是關于Javascript6中字符串的四個新用法,大家都學會了嗎?希望這篇文章對大家能有所幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答