字符串的新增方法→startsWith() endsWith() Includes() repeat()

28 篇文章 0 订阅
<!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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值