首頁  >  文章  >  web前端  >  ES6字串超實用的知識介紹

ES6字串超實用的知識介紹

不言
不言轉載
2019-03-11 16:33:181517瀏覽

這篇文章帶給大家的內容是關於ES6字串超實用的知識介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

模板字串

1.可寫多行字串

2.使用${}新增變數

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

模板字串甚至還能巢狀

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

標籤模板:

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)"

literals參數為非變數組成的數組,變數原本位置為數組中各元素之間,上面這個例子展示了,如何將各個參數按照原來的位置拼合回去。

  • 「標籤範本」的一個重要應用,就是過濾 HTML 字串,防止使用者輸入惡意內容。

實用方法集

1.字串的遍歷器介面
for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"
2.includes(), startsWith(), endsWith ()
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

這三個方法都支援第二個參數,表示開始搜尋的位置。

let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

上面程式碼表示,使用第二個參數n時,endsWith的行為與其他兩個方法有所不同。它針對前n個字符,而其他兩個方法針對從第n個位置直到字串結束。

3.repeat()

repeat方法傳回一個新字串,表示將原始字串重複n次。

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

4.padStart(),padEnd()

padStart()

用於頭部補全,

padEnd()

用於尾部補全。

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

 

#

以上是ES6字串超實用的知識介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除