[ES6]字符串——笔记1

110 阅读1分钟

一、模板字符串(常用)

let x = "World"
let str = `hello ${x}!`

二、判断某元素是否包含在字符串里

1、str.includes(x)

判断str中是否存在元素x

        let str = "Hello World!"
        console.log(str.includes("World"));//true
        console.log(str.includes('no'));//false

2、str.startsWith(x)

判断元素x是否在str的头部

        let str = "Hello World!"
        console.log(str.startsWith("H"));//true
        console.log(str.startsWith('ell'));//false

3、str.endsWith(x)

判断元素x是否在str尾部

        let str = "Hello World!"
        console.log(str.endsWith("d!"));//true
        console.log(str.startsWith('or'));//false

三、str.repeat(n)

返回一个重复打印n次str的新字符串

console.log("Hello ".repeat(3));//Hello Hello Hello 

四、补全字符串

1、str1.padStart(n,str2)

指定str1长度为n; 当str1长度>=n,原样输出str1; 当str1长度<n,在str1头部补上(m个)str2,若str2加上str1的长度超过n,就截取str2右边部分字符串。

        console.log("1".padStart(3,"22"));//221
        console.log("1".padStart(2,"234"));//21
        console.log("1xxx".padStart(2,"234"));//1xxx

2、str1.padEnd(n,str2)

指定str1长度为n; 当str1长度>=n,原样输出str1; 当str1长度<n,在str1的尾部补上(m个)str2,若str2加上str1的长度超过n,就截取str2右边部分字符串。

        console.log("1".padEnd(3,"22"));//122
        console.log("1".padEnd(2,"234"));//12
        console.log("1xxx".padEnd(2,"234"));//1xxx

五、消除字符串头或尾部的空格

str.trim():消除字符串str头尾两端的空格;

str.trimStart():消除字符串str头部的空格;

str.trimEnd():消除字符串str尾部的空格。

let str ="   111   "
       console.log(str);
       console.log(str.trim());
       console.log(str.trimStart());
       console.log(str.trimEnd());

image.png

六、字符串的元素匹配替换

1、str.replace(x,y):把str中的第一个元素x替换成y

       let str ="121223111"
       console.log(str.replace("1","x"));//x21223111

2、str.replaceAll(x,y):把str中的所有元素x替换成y

       let str ="121223111"
       console.log(str.replaceAll("1","x"));//x2x223xxx

七、str.at(n)字符串索引

       let str="Hello World!"
       console.log(str.at(1));//e
       console.log(str.at(-1));//!
       console.log(str.at(13));//undefined