es6新增字符串方法

水深无声 2023-07-10 15:40 47阅读 0赞

个人学习记录
includes():返回布尔值,表示是否找到了参数字符串。

  1. let str="Hello world!"
  2. str.includes('Hello') // true
  3. //还可以这样
  4. let arr=['a','b','c','d','e']
  5. arr.includes('a')//true
  6. //还可以有第二个参数
  7. str.includes('Hello',6)//false
  8. str.includes('world',6)//true
  9. arr.includes('c',2)//true

repeat():返回一个新字符串,表示将原字符串重复n次(n为0或者正整数)

  1. 'hello'.repeat(2) // "hellohello"
  2. 'hello'.repeat(2.1) // "hellohello"
  3. 'hello'.repeat(‘he’) // ""
  4. 'hello'.repeat(0) // ""

padStart()用于头部补全,padEnd()用于尾部补全
第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串,默认为空格。如果原字符串的长度,等于或大于最大长度,则字符串补全不生效,返回原字符串。如果用来补全的字符串与原字符串,两者的长度之和超过了最大长度,则会截去超出位数的补全字符串。

  1. 'x'.padStart(5, 'ab') // 'ababx'
  2. 'x'.padEnd(5, 'ab') // 'xabab'

trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格
返回新字符串,不会修改原始字符串。

  1. const s = ' abc ';
  2. s.trim() // "abc"
  3. s.trimStart() // "abc "
  4. s.trimEnd() // " abc"

发表评论

表情:
评论列表 (有 0 条评论,47人围观)

还没有评论,来说两句吧...

相关阅读