字符串扩展

2018-10-17  本文已影响0人  梦里coding

ES6加强了对字符串的扩展,这里小编只对在工作中会用到或者重要的部分进行总结。

1、for...of遍历字符串

for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"

es6为字符串添加了遍历器接口,使得字符串可以被for...of进行循环遍历

2、includes() 判断一个字符串或数组是否包含一个指定的值

let s = 'Hello world!';
s.includes('o') //true

s.includes('Hello', 6) // false

3、 startsWith(), endsWith() 判断字符串的头部和尾部

let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true

4、repeat()复制字符串

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // 

5、padStart(),padEnd()头部补全和尾部补全

如果某个字符串不够指定长度,就会在尾部和头部补全

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

padStart的常见用途是为数值补全指定位数。下面代码生成 10 位的数值字符串

'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"

6、模板字符串

从前这样写:

$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);

在ES6中,可以使用string来展示字符串,而变量则可以是一个${xx}来标识

$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);
上一篇 下一篇

猜你喜欢

热点阅读