1. 程式人生 > 實用技巧 >關於ES6的字串

關於ES6的字串

字串

一. 新增的方法

1.String.fromCodePoint()

由於ES5中的String.fromCharCode()方法(用於從Unicode碼點返回對應字元),但只能識別碼點小於0xFFFF的字元。

ES6提供的String.fromCodePoint()彌補了該不足。

2. String.raw()

該方法返回一個斜槓都被轉義(即斜槓前面再加一個斜槓)的字串,往往用於模板字串的處理方法。

String.raw`Hi\n${2+3}!`
// 實際返回 "Hi\\n5!",顯示的是轉義後的結果 "Hi\n5!"

String.raw`Hi\u000A!`;
// 實際返回 "Hi\\u000A!",顯示的是轉義後的結果 "Hi\u000A!"

3. includes(),startwith(),endwith()

傳統上,JavaScript 只有indexOf方法

4. repeat()

5. padStart(),padEnd()

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

    'x'.padEnd(5, 'ab') // 'xabab'
    'x'.padEnd(4, 'ab') // 'xaba'

padStart()的常見用途是為數值補全指定位數。下面程式碼生成 10 位的數值字串。

    '1'.padStart(10, '0') // "0000000001"
    '12'.padStart(10, '0') // "0000000012"
    '123456'.padStart(10, '0') // "0000123456"

另一個用途是提示字串格式。

    '12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
    '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

6. trimStart(),trimEnd()

去除頭部空格,去除尾部空格

二. 模板字串

  1. 傳統的字串輸出模板
    let a = 'hello'
    let b = 'world'
    
  2. 模板字串(template string) 是增強版的字串, 用反單引號(`)標識。
    //普通字串
    `hello world`

    // 多行字串
    `welcome to
    the world`

    console.log( `welcome to
    the world`);
    //  welcome to
    //       the world

    // 字串中嵌入變數
    let name = 'Tom' , time = 'today';
    let str = `Hello ${name}, how are you ${time}?`
     console.log(str); //Hello Tom, how are you today?

注意: 在使用模板字串表示多行字串時,所有的空格,縮排,換行都被保留在輸出之中。

  • 模板字串中,嵌入變數時,要把變數名寫在 ${}中

  • 括號內可以放入任意的javascript表示式,可以進行運算,以及引用物件屬性

    let a = 1;
    let b = 2;

    ` ${a} + ${b} = ${a+b}` // 1 + 2 = 3

    ` ${a+1} + ${b*2} = ${(a+b)*2}` //  2 + 4 = 6

    let obj = {x: 1, y: 2};
    `${obj.x + obj.y}`
    // "3"
  • 呼叫函式
    function fn() {
    return "Hello World";
    }

    `foo ${fn()} bar`
    // foo Hello World bar

參考文件:https://es6.ruanyifeng.com/#docs/string