关于ES6的字符串

字符串

一. 新增的方法

1.String.fromCodePoint()

由于ES5中的String.fromCharCode()方法(用于从Unicode码点返回对应字符),但只能识别码点小于0xFFFF的字符。

ES6提供的String.fromCodePoint()弥补了该不足。

2. String.raw()

该方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串,往往用于模板字符串的处理方法。

String.raw`Hi
${2+3}!`
// 实际返回 "Hi\n5!",显示的是转义后的结果 "Hi
5!"

String.raw`Hiu000A!`;
// 实际返回 "Hi\u000A!",显示的是转义后的结果 "Hiu000A!"

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

原文地址:https://www.cnblogs.com/Heiofungming/p/13336976.html