字符串的新增方法

77 阅读1分钟

1. includes()、startsWith()、endsWith()

  • includes() :返回布尔值,表示是否找到了参数字符串
  • startsWith() :返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith() :返回布尔值,表示参数字符串是否在原字符串的尾部。
let s = 'Hello world!'
console.log(s.startsWith('Hello'))  //true
console.log(s.endsWith('!'))  //true
console.log(s.includes('o'))  //true

这三个方法都支持第二个参数,表示开始搜索的位置

let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

2. repeat()

  • repeat方法返回一个新字符串,表示将原字符串重复n
console.log('x'.repeat(3))  //xxx
console.log('hello'.repeat(2))  //hellohello