JavaScript 6 里关于字符串的几个新用法

本文将要介绍在JavaScript 6(ES6)里出现的一个关于字符串操作的语法特征。

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 '
阅读余下内容
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号