ES6类型扩展-字符串扩展

本文详细介绍ES6对字符串的扩展

字符串识别

在ES6之前,常使用indexOf()方法判断一个字符串中是否包含另一个字符串。ES6新增加了3个方法让开发者更方便的识别字符串。

【includes(str, index)】字符串包含给定文本时返回true,否则返回false。str表示要查找的文本,index表示从哪个位置查找。

【startsWidth(str, index)】 字符串的起始位置是给定文本时返回true, 否则返回false。 str表示要查找的文本,index表示从哪个位置查找。

【endsWidth(str, index)】 字符串的结束位置是给定文本时返回true, 否则返回false。 str表示要查找的文本,index表示从哪个位置查找。

var test = 'Hello world!';
console.log(test.startsWith('Hello')); // true
console.log(test.endsWith('!')); // true
console.log(test.includes('o')); // true

console.log(test.startsWith('e')); // false
console.log(test.endsWith('d')); // false
console.log(test.includes('x')); // false

console.log(test.startsWith('o', 4)); // true
console.log(test.endsWith('o', 5)); // true
console.log(test.includes('o', 8)); // false

index参数是可选的, 如果不传该参数, includes() 和startsWidth() 方法会自左向右查找。 endsWidth()方法自右向左查找。如果传了参数, includes() 和startsWidth() 方法从index位置查找, endsWidth() 方法从str.length - index位置查找。

由于这三个方法只能返回一个布尔值,所以要想获得字符的具体位置,还是需要indexOf() 和 lastIndexOf()方法。

另外这三个方法如果传入了正则表达式,会抛出错误。而indexOf() 和 lastIndexOf()方法会把正则表达式转换成字符串,然后查找位置。

字符串重复

【repeat(num)】repeat()方法用于复制字符串,它接收一个num参数,表示要复制的次数。num大于等于0。

'wmui'.repeat(0) // ''
'wmui'.repeat(3) // 'wmuiwmuiwmui'

字符串补全

字符串补全函数有两个:padStart()和padEnd()

【padStart(minLength,str)】padStart()函数接收两个参数:第一个表示字符串的最小长度;第二个参数可选,表示用来补全的字符串。它会把str添加到原字符串的前面。

【padEnd(minLength,str)】padEnd()函数接收两个参数:第一个表示字符串的最小长度;第二个参数可选,表示用来补全的字符串。它会把str添加到原字符串的后面。

'hello'.padStart(10,'world') // 'worldhello'
'hello'.padStart(4,'world') // 'hello'

'hello'.padEnd(10,'world') // 'helloworld'
'hello'.padEnd(4,'world') // 'hello'

如果未提供第二个参数时,默认使用空格补全字符串。

'hello'.padStart(10) // "     hello"
'hello'.padEnd(10) // "hello     "

如果原字符串的长度加上str的长度超过了minLength,超出的str字符会被截掉。

'hello'.padStart(7, 'world') // "wohello"
posted @ 2021-09-29 11:33  wmui  阅读(46)  评论(0编辑  收藏  举报