es6字符串新增方法

1. includes() 表示是否找到了参数字符串, 返回布尔值。

const str = 'hello world'
const res = str.includes('e')  // true
const res2 = str.includes('a')  //false
const res3 = str.includes('eo')  //false
const res4 = str.includes('he')  //true
注意:includes()方法,找到返回true, 否则为false。

2. startsWith() 表示参数字符串是否在原字符串的头部, 返回布尔值。

const str = "hello world"
const res = str.startsWith('h')  //true
const res2 = str.startsWith('e')  //false

3. endsWith() 表示参数字符串是否在原字符串的尾部, 返回布尔值。

const str = "hello world"
const res = str.endsWith('d')  //true
const res2 = str.endsWith('h')  //false

4. repeat() 表示将原字符串重复n次,返回一个新字符串。

const str = 'curry'
const res = 'x'.repeat(2)  // 'xx'
const res2 = 'hello'.repeat(2)  //'hellohello'
const res3 = str.repeat(2)  //currycurry

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

const str = '    hello    '
const res = str.trimStart()  //'hello    '
const res2 = str.trimEnd()  //'    hello'

6. replaceAll() 替换所有匹配的字符串, 返回一个新字符串,不会改变原字符串。

const str = 'aabbccddbb'
const res = str.replaceAll('b', 'w')  //'aawwccddww'

7. at() 接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。

const str = 'abcde'
const res = str.at(2)  //c
const res2 = str.at(-1)  //e
posted @ 2022-03-24 16:30  SKa-M  阅读(50)  评论(0编辑  收藏  举报