ES6新增操作字符串的七种方法

让我为大家介绍一下ES6新增操作字符串的七种方法吧!

1.includes() 重点

返回布尔值,判断是否找到参数字符串

    let str = "hello str"
    // 找到返回true
    console.log(str.includes("h")) // true
    // 没找到返回false
    console.log(str.includes("a")) // false

2.startsWith()

返回布尔值,判断参数字符串是否在原字符串的头部

    let str = "hello str"
    // h在字符串的头部返回true
    console.log(str.startsWith("h"))//true
    // e不在头部返回false
    console.log(str.startsWith("e"))//false

3.endsWith()

返回布尔值,判断参数字符串是否在原字符串的尾部

    let str = "hello str"
    // r在字符串的尾部返回true
    console.log(str.endsWith("r")) // true
    // h不在字符串的尾部返回false
    console.log(str.endsWith("h")) // false

4.repeat(number)

返回新的字符串,表示将字符串重复指定次数返回

    let str = "hello str"
    console.log(str.repeat(2)) //hello strhello str

5.padStart(总长度,“填充的字符串”)

返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串

    let str = "hello str"
    // 现在我们str的长度为9
    // 我们限定了总长度为10 我们在字符串最前面添加 一直添加到总长度为10
    // 如果未填充字符串 字符串不变
    console.log(str.padStart(10,"123")) //1hello str

6.padEnd(总长度,“填充的字符串”)

返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串

    let str = "hello str"
    // 现在我们str的长度为9
    // 我们限定了总长度为10 我们在字符串最后面添加 一直添加到总长度为10
    // 如果未填充字符串 字符串不变
    console.log(str.padEnd(10, "123")) //hello str1

7.模板字符串

大家如果想更好的了解模板字符串的使用,可以阅读本人的这篇模板字符串的基本使用

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

posted @ 2023-11-01 14:45  一叶知秋04  阅读(12)  评论(0编辑  收藏  举报  来源