ES6字符串新出的功能

105 阅读2分钟
  • includes() :返回布尔值,判断是否能找到参数字符串。
var str='here3bw'
var re=str.includes("3b")
var re1=str.includes('jej')
console.log(re,re1)

image.png

  • startsWith() :返回布尔值,判断参数字符串是否在原字符串的头部。
var str='here3bw'
var re=str.startsWith('her')
var re1=str.startsWith("e3",3)//d第二个参数表示从下标几开始算
var re2=str.startsWith('er')
console.log(re,re1,re2)

image.png

  • endsWith() :返回布尔值,判断参数字符串是否在原字符串的尾部。
var str='here3bw'
var re=str.endsWith('3bw')
var re1=str.endsWith("e3",5)//第二个参数表示从那个参数结尾
var re2=str.endsWith('er')
console.log(re,re1,re2)

image.png

上面这三个方法只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf 。

  • repeat() :返回新的字符串,表示将字符串重复指定次数返回。
    如果参数是负数或者 Infinity ,会报错:
var str='here3bw-'
var re=str.repeat(3)//参数代表重复几次
var re1=str.repeat(2.7)//如果参数是小数,向下取整
var re2=str.repeat(-0.9)//如果参数是 0 至 -1 之间的小数,会取整为-0 ,等同于 repeat 零次
var re3=str.repeat(NaN)//如果参数是 NaN,等同于 repeat 零次
var re4=str.repeat('3')//如果传入的参数是字符串,则会先将字符串转化为数字
console.log(re)
console.log(re1)
console.log(re2)
console.log(re3)
console.log(re4)

image.png

  • padStart:返回新的字符串,表示用参数字符串从头部补全原字符串。
  var str = 'hw'
  var re=str.padStart(5,"o")
  var re1=str.padStart(5)//第二个参数不写默认用空格填充
  console.log(re,re1)

image.png

  • padEnd:返回新的字符串,表示用参数字符串从尾部补全原字符串。
   var str = 'hw'
  var re=str.padEnd(5,"o")
  var re1=str.padEnd(5)//第二个参数不写默认用空格填充
  var re2=str.padEnd(5,"ofvtsc")//如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串
  console.log(re,re1,re2)

image.png

  • 模板字符串相当于加强版的字符串,用反引号 ` ,除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式。
  var a='hello'
  function fn(){
    return "I am fine"
  }
  var str = 'hwgrer,gldsv'//普通字符串
  var str1=`hello,
  nice to meet you`//字符串可以换行
  var str2=`${a},wrold`//字符串中可以加变量
  var str3=`${fn()}`
 console.log(str)
 console.log(str1)
 console.log(str2)
 console.log(str3)

image.png