zl程序教程

您现在的位置是:首页 >  后端

当前栏目

09.字符串新增方法

方法 字符串 新增 09
2023-09-27 14:23:04 时间
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>字符串新增方法</title>
</head>
<body>
    <script>

        // test1: includes(),startsWith(),endsWith(),查看字符串是否在原字符串某个位置中
        // 传统js只有indexOf用来判断一个字符串是否在另一个字符串中
        let s = "hello"
        console.log(s.includes('he'));
        console.log(s.startsWith('he'));
        console.log(s.endsWith('he'));


        //支持指定从某个位置开始搜索
        console.log(s.includes('l',2));
        console.log(s.startsWith('l',2));
        console.log(s.endsWith('l',2));


        //test2: repeat() 返回新字符串,原字符串重复n次
        console.log(s.repeat(3));


        //test3:
        //padStart(),padEnd():自动补全,第一个参数指定长度,第二个使用补全的字符串
        console.log('x'.padStart(5,'ab'));
        console.log('x'.padStart(4,'ab'));//若不够时,从a开始到b补全
        console.log('x'.padEnd(5,'ab'));
        console.log('x'.padEnd(4,'ab'));//若不够时,从a开始到b补全

        //test4:
        //trimStart(),trimEnd(),消除开头或结尾的空格,返回新字符串
        let t = '    it bai    '
        console.log(t.trim());
        console.log(t.trimStart());
        console.log(t.trimEnd());

        //test5:
        //at():返回指定位置的字符,支持负索引;超出字符串范围,返回undefined
        let str = 'helloooo'
        console.log(str.at(1));
        console.log(str.at(-1));
        console.log(str.at(100));



    </script>
</body>
</html>