【ES6(2015)】String

1. Unicode表示法

ES6 加强了对 Unicode 的支持,允许采用\uxxxx形式表示一个字符,其中xxxx表示字符的 Unicode 码点。

"\u0061" // "a"

但是,这种表示法只限于码点在\u0000~\uFFFF之间的字符。超出这个范围的字符,必须用两个双字节的形式表示。

"\uD842\uDFB7"
// "𠮷"

"\u20BB7"
// " 7"

如果直接在\u后面跟上超过0xFFFF的数值(比如\u20BB7),JavaScript 会理解成\u20BB+7。由于\u20BB是一个不可打印字符,所以只会显示一个空格,后面跟着一个7。

有了这种表示法之后,JavaScript 共有 6 种方法可以表示一个字符。

'\z' === 'z' // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true

2. 遍历器接口

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

for (let item of 'oh,es6 is 666!') {
    console.log(item)
}

3. 模板字符串

先看看ES5中处理字符串复杂的方式:

// 字符串很长要换行,处理不好就会导致程序语法错误

// 字符串中有变量或者表达式,拼接字符串很麻烦,稍不留意就错了
var name = "xiaoming"
var age = 18
var res = 'Hello, my name is' + name + ' I\'m' + age
console.log(res)

ES6 中引入字符串字面量来解决字符串拼接问题:

// 换行问题
`string text line 1
 string text line 2`

// 字符串中包含变量或表达式,拼接
`Hello, my name is ${name} I'm ${age}`

ES6 中还引入了标签模板来解决字符串复杂逻辑:

// 定义标签函数
function tag(literals, ...substitutions) {
  // 返回一个字符串
}
var a = 5;
var b = 10;

tag`Hello ${ a + b } world ${ a * b }`;
// 等同于
tag(['Hello ', ' world ', ''], 15, 50);

4. 扩展方法

  • String.prototype.fromCodePoint()
    从 Unicode 码点返回对应字符,并且可以识别大于0xFFFF的字符
// ES5
console.log(String.fromCharCode(0x20BB7))

// ES6
console.log(String.fromCodePoint(0x20BB7))
  • String.prototype.includes()
// ES5 使用indexOf方法判断是否存在,不存在返回-1,存在返回对应下标
const str = 'hello'
console.log(str.indexOf('lo'))

// ES6提供了includes方法来判断,返回boolean类型的值
const str = 'hello'
console.log(str.includes('lo'))
  • String.prototype.startsWith()
    判断参数字符串是否在原字符串的头部, 返回boolean类型的值。
const str = 'hello'
console.log(str.startsWith('he'))
  • String.prototype.endsWith()
    判断参数字符串是否在原字符串的尾部, 返回boolean类型的值。
const str = 'hello'
console.log(str.endsWith('lo'))
  • String.prototype.repeat()
    repeat方法返回一个新字符串,表示将原字符串重复n次。
const str = 'hello'
const newStr = str.repeat(3)
console.log(newStr) // hellohellohello
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值