字符串扩展

1.str.includes() str.startsWith() str.endsWith()

{
    let str = 'string';
    // 判断字符串中是否包含某一字符
    console.log('includes', str.includes('r')); // true
    // 判断字符串是否以某一字符开始
    console.log('start', str.startsWith('str')); // true
    // 判断字符串是否以某一字符结束
    console.log('end', str.endsWith('ng')); // true
}

2.str.repeat()

{
    // repeat方法用于字符串复制
    let str = 'abc';
    console.log(str.repeat(3)); // abcabcabc
}

3.str.padStart() 和 str.padEnd()

{
    // 字符串补白,日期、时间、金额经常用到
    console.log('1'.padStart(2, '0')); // 01
    console.log('12'.padStart(2, '0')); // 12
    console.log('1'.padEnd(2, '0')); // 10
}

4.模板字符串

{
    let name = 'can';
    let info = 'hello beautiful girl';
    let temp = `i am ${name}, ${info}`;
    console.log(temp); // i am can, hello beautiful girl
}

5.标签模板,作用:防止XSS攻击,处理多语言转换

{
    let user = {
        name: 'can',
        info: 'hello beautiful girl'
    };
    abc`i am ${user.name}, ${user.info}`;

    function abc(s, v1, v2) {
        console.log(s, v1, v2); // ["i am ", ", ", ""]  "can"  "hello beautiful girl"
        return s + v1 + v2;
    }
}

6.String.raw

{
    // raw方法对\做了转义
    console.log(String.raw`Hi\n${1 + 2}`);  // Hi\n3
    console.log(`Hi\n${1 + 2}`);
    // Hi
    // 3
}

lxcan
337 声望32 粉丝