ES6温习

1、模版字符串

    模版字符串 使用反引号(`)标识。

    之前关于字符串的拼接,如果我们想自字符串中添加变量,我们需要把字符串从添加变量的位置隔开,用"+"把两部分加上变量连接起来。

    在模版字符串中,我们只需要将用 ${变量} 将变量放入字符串中,即可。

var a = 12;

var str = "I'm " + a + " years old";     // I'm 12 years old
var strES6 = `I'm ${a} years old`;    // I'm 12 years old
var strES6 = `I'm ${ a*2 } years old`;  // "I'm 24 years old"

  

2、String 新增方法

  • includes 类似 indexof。不同之处在于 indexof 返回的是位置信息,若没有则返回-1;includes 返回的则是 Boolean 类型,若有则返回 true,没有则返回 false。
str
//"I'm 12 years old"

str.includes("'m")
// true

str.includes("QQQ")
// false
  • startWithendWith 两者的返回类型都是 Boolean 类型。

    startsWith 返回的是被检索字符串头部位置是否存在参数字符串,有则返回 true,反之返回 false。

            endsWith 返回的是被检索字符串尾部位置是否存在参数字符串,有则返回 true,反之返回 false。

str
// "I'm 12 years old"

str.startsWith("I'")
// true

str.startsWith("year")
// false

str.endsWith("old")
// true

str.endsWith("year")
// false
  • repeat 返回一个将原字符串重复n次新字符。 n = 0 或者 -1<n<0,则默认重复0次。n<-1 则会报错
str;                      // "I'm 12 years old"

str.repeat(3);       // "I'm 12 years oldI'm 12 years oldI'm 12 years old"

str.repeat(1.5);    // "I'm 12 years old"

str.repeat(0)        // ""

str.repeat(-0.9)    // ""
  • padStartpadEnd 函数有两个变量,第一个参数是 字符串长度;第二个参数是 补全的字符串,若第二个参数为空,则补全空格

    padStart 若字符串长度小于指定长度,则在头部使用 补全字符串 对字符串进行补全。

    padEnd 若字符串长度小于指定长度,则在尾部使用 补全字符串 对字符串进行补全。

str = "go"
// "go"

str.padStart(6, "asd")
// "asdago"

str.padEnd(8, "asd")
// "goasdasd"

str.padEnd(-6, "asd")
// "go"

    padStart 可以用来补全指定位数。生成 10 位的数值字符串。

str = "9"
// "9"

str.padStart(10, "0")
// "0000000009"
  • trimStart,trimEnd  它们返回的都是新字符串,不会修改原始字符串。

    trimStart 消除字符串头部的空格。

    trimEnd 消除尾部的空格。

let a = '  abc  ';

a.trim() // "abc"
a.trimStart() // "abc  "
atrimEnd() // "  abc"
原文地址:https://www.cnblogs.com/Lyh1997/p/12747058.html