005 字符串新增方法
includes(),startsWith(),endsWith()
传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6又提供了三种新方法。
①includes():返回布尔值,表示是否找到了参数字符串
②startsWith():返回布尔值,表示参数字符串是否在原字符串的头部
③endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部
let s ='Hello world!';
s.startswith('Hello')//true
s.endswith('!')//true
s.includes('o')//true
这三个方法都支持第二个参数,表示开始搜索的位置
let s='Hello world!';
s.startswith('world',6)//true
s.endswith('Hello',5)//true
s.includes('Hello',6)//false
1、repeat()
repeat方法返回一个新字符串,表示将原字符串重复n次。
'x'.repest(3)//"xxx"
'hello'.repeat(2)//"hellohello"
'na'.repeat(0)//""
2、padStart(),padEnf()
ES2017引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全。
'x'.padStart(5,'ab')//'ababx'
'x'.padStart(4,'ab')//'abax'
'x'.padEnd(5,'ab')//'xabab'
'x'.padEnd(a,'ab')//'xaba'
3、trimStart(),trimEnd()
ES2019对字符串实例新增了trimStart()和trimEnd()这两个方法。它们的行为与trim()一致,trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。
const s =' zifuchuan ';
s.trim()//"zifuchuan"
s.trimStart()//"zifuchuan"
s.trimEnd()//"zifuchuan"
4、at()
at()方法接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。
const str ='hello';
str.at(1)//"e"
str.at(-1)//"o"
温馨提示:如果参数位置超出了字符串范围,at()返回undefined



浙公网安备 33010602011771号