枯燥的js 字符串函数

<script>
       let name = "zyqqwe"
       console.log(name.length);
       console.log(name.toUpperCase());
       console.log(name.toLowerCase());
       let site = "  23123 ";
       console.log(site.length);
       console.log(site.trim().length);//trim就是消除空格
    </script>

在这里插入图片描述

字符串截取

<script>
       let hd = "zyqqwqweqwee"
    //slice substr substring
    console.log(hd.slice(1))
    console.log(hd.substring(1))
    console.log(hd.substr(1));
    </script>

当只有一个参数的时候,都表示从第几个后开始截取,三者相差不大。

console.log(hd.slice(1,3));
    console.log(hd.substring(1,3))
   console.log(hd.substr(1,3));

在这里插入图片描述

当slice,substring加上第二个参数,就表示从第几个后开始截取到第几个。
而substr的第二个参数则表示,从第几个后开始截取几个
在这里插入图片描述

 <script>
       let hd = "zyqqwqweqwee"
    //slice substr substrin
    console.log(hd.slice(-3));
    console.log(hd.substring(-3))
    console.log(hd.substr(-3));
    </script>

当参数变成负数时。slice和substr从后面开始算,而substring相当于从0开始
在这里插入图片描述

检索字符串

 const hd = "zyqhstsl";
       console.log(hd.includes("s",1));

第一个参数为要检测值(可以是字符串),第二个表示从第几个开始,负数也行,返回布尔值。
在这里插入图片描述

<script>
       const word= ["javascript","tainanle"];
        const string = "javascript太难了(tainanle)";
        const status = word.some(word=>{
            console.log(word);
            return string.includes(word);
        })
        if(status){
            console.log("找到了关键词");
        }
    </script>

some函数有点像短路运算。找到了一个为真,就会返回。

在这里插入图片描述
修改word的第一个词。
在这里插入图片描述
some函数就会继续查找。

reduce

<script>
       const word = ["php","css"];
       const string = "我喜欢学习php与css知识";
       const replaceString =word.reduce((pre,word)=>{//会将string传给pre变量
            return pre.replace(word,`<a href="#">${word}</a>`);
       },string)
       document.body.innerHTML+=replaceString;
    </script>

在这里插入图片描述
reduce函数会循环数组里的个数次,搜索所有符合word数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值