1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 10:22:23 +00:00

add string/padStart & padEnd

This commit is contained in:
ruanyf 2015-11-28 19:27:17 +08:00
parent f6026e153d
commit c6b9b0ce0d
3 changed files with 30 additions and 1 deletions

View File

@ -93,7 +93,7 @@ $ node --v8-options | grep harmony
上面命令的输出结果,会因为版本的不同而有所不同。
我写了一个[ES-Checker](https://github.com/ruanyf/es-checker)模块用来检查各种运行环境对ES6的支持情况。访问[ruanyf.github.io/es-checker](http://ruanyf.github.io/es-checker),可以看到您的默认浏览器支持ES6的程度。运行下面的命令可以查看本机支持ES6的程度。
我写了一个[ES-Checker](https://github.com/ruanyf/es-checker)模块用来检查各种运行环境对ES6的支持情况。访问[ruanyf.github.io/es-checker](http://ruanyf.github.io/es-checker)可以看到您的浏览器支持ES6的程度。运行下面的命令可以查看本机支持ES6的程度。
```bash
$ npm install -g es-checker

View File

@ -48,6 +48,7 @@
- Addy Osmani, [Getting Literal With ES6 Template Strings](http://updates.html5rocks.com/2015/01/ES6-Template-Strings): 模板字符串的介绍
- Blake Winton, [ES6 Templates](https://weblog.latte.ca/blake/tech/firefox/templates.html): 模板字符串的介绍
- Peter Jaszkowiak, [How to write a template compiler in JavaScript](https://medium.com/@PitaJ/how-to-write-a-template-compiler-in-javascript-f174df6f32f): 使用模板字符串,编写一个模板编译函数
- Axel Rauschmayer, [ES.stage3: string padding](http://www.2ality.com/2015/11/string-padding.html)
## 正则

View File

@ -297,6 +297,34 @@ s.includes('Hello', 6) // false
'na'.repeat('3') // "nanana"
```
## padStart()padEnd()
ES7推出了字符串补全长度的功能。如果某个字符串不够指定长度会在头部或尾部补全。`padStart`用于头部补全,`padEnd`用于尾部补全。
```javascript
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
```
上面代码中,`padStart``padEnd`一共接受两个参数,第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串。
如果原字符串的长度,等于或大于指定的最小长度,则返回原字符串。
```javascript
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
```
如果省略第二个参数,则会用空格补全长度。
```javascript
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
```
## 模板字符串
传统的JavaScript语言输出模板通常是这样写的。