微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ES6系列--【ES6 新增字符串方法】

es6 新增字符串方法

es6新增了4个字符串处理的方法:startsWith,endsWith,includes,repeat。

1、简单使用

  • includes()返回布尔值,表示是否找到了参数字符串
  • startsWith()返回布尔值,表示参数字符串是否在源字符串的头部
  • endsWith()返回布尔值,表示参数字符串是否在源字符串的尾部

复制代码

 let str="lxy";
        //字符串是否以某个字符开头
        console.log(str.startsWith('l'));//true
        console.log(str.startsWith('x'));//false
        //字符串是否以某个字符结尾
        console.log(str.endsWith('x'));//false
        console.log(str.endsWith('y'));//true
        //字符串是否包含某个字符
        console.log(str.includes('x'));//true
        console.log(str.includes('z'));//false
        //repeat()重复某个字符串几次
        console.log(str.repeat(3));//lxylxylxy
        console.log(str.repeat(5));//lxylxylxylxylxy

复制代码

2、第2个参数

includes(),startsWith(),endsWith()都支持第2个参数。

使用第2个参数n时,endsWith的行为与其他两个方法有所不同。

  • endsWith针对前n个字符。
  • 其他2个方法:针对从第n个位置直到字符串结束的字符。
var s="Hello World!";
s.startsWith('world',6);//true
s.endsWith('hello',5);//true
s.includes('hello',6);//false

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐