Add string methods → startsWith () endsWith () Includes () repeat ()

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>字符串的新增方法</title>
</head>

<body>
    <script>
        const id = '43062319980711477x';
        const fan = 'I love LoMan.';

        /*
        startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
        */
        console.log(id.startsWith('43'));//true
        console.log(id.startsWith('3'));//false

        //设想:我现在想要知道第二位是不是3,你可以像下面这样做
        console.log(id.startsWith('3', 1));//true

        //startsWith方法是大小写敏感的。
        console.log(fan.startsWith('I'));//true
        console.log(fan.startsWith('i'));//false




        /*
        endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
        */

        //设想:你想知道id变量后面是不是x,简单做法可以这样。
        console.log(id.endsWith('x'))//true

        //endsWith方法也可以查询字符串的位置,从左到右数从1开始数。
        console.log(id.endsWith('30', 3))//true
        console.log(id.endsWith('623', 6))//true
        console.log(fan.endsWith('I', 1))//true





        /*
        includes():返回布尔值,表示是否找到了参数字符串。
        注意:针对从第n个位置直到字符串结束
        */
        console.log(fan.indexOf('LoMan') !== -1);//true
        console.log(fan.indexOf('LoMan'));//7

        console.log(fan.includes('LoMan'));//true

        //设想:你想知道第7位开始之后(含第7位)有没有LoMan
        console.log(fan.includes('LoMan', 7));//true
        //设想:你想知道第8位开始之后有没有LoMan
        console.log(fan.includes('LoMan', 8));//false





        /*
        repeat方法返回一个新字符串,表示将原字符串重复n次。
        */
        console.log('xyz'.repeat(2));//xyzxyz

        // const heading=`${`=`.repeat(5)} ${fan} ${'='.repeat()}

        //体验一下字符串对齐
        function padder(string,length=100){
            return `${` `.repeat(Math.max(length-string.length,0))} ${string}`
        }
        console.log(padder(id));
        console.log(padder(fan));
    </script>
</body>

</html>

 

Guess you like

Origin blog.csdn.net/JEFF_luyiduan/article/details/91896476