ES6 字符串新增方法

字符串新增方法

String.fromCodePoint()

从 Unicode 码点返回对应字符,方法可以识别大于0xFFFF的字符

String.fromCharCode(0x20BB9)  // "ஹ"
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y' // true
String.raw()

方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串

String.raw`Hi\u000A!`;
// 实际返回 "Hi\\u000A!",显示的是转义后的结果 "Hi\u000A!"
codePointAt()

测试一个字符由两个字节还是由四个字节组成的最简单方法

function is32Bit(c) {
  return c.codePointAt(0) > 0xFFFF;
}
is32Bit("𠮷") // true
is32Bit("a") // false
includes()

返回布尔值,表示是否找到了参数字符串

let s = 'Hello world!';
s.includes('w') // true
s.includes('i') // false
startsWith()

返回布尔值,表示参数字符串是否在原字符串的头部。

let s = 'Hello world!';
s.startsWith('He') // true
s.startsWith('Hi') // false
endsWith()

返回布尔值,表示参数字符串是否在原字符串的尾部。

let s = 'Hello world!';
s.endsWith('!') // true
s.endsWith('d') // false

includes、startsWith、endsWith支持第二个参数,表示开始搜索的位置

let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
repeat()

返回一个新字符串,表示将原字符串重复n

'ha'.repeat(3) // 'hahaha'
'hi'.repeat(0) // ''
padStart(),padEnd()

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

'x'.padStart(5, 'ha') // 'hahax'
'x'.padStart(4, 'ha') // 'hahx'

'x'.padEnd(5, 'ha') // 'xhaha'
'x'.padEnd(4, 'ha') // 'xhah'

'x'.padStart(4) // '   x'
'x'.padEnd(4) // 'x   '

提示字符串格式。

'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'12-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-12-12"
trimStart(),trimEnd()

消除字符串头部的空格和消除尾部的空格

const s = '  abc  ';
s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"
replaceAll()

一次性替换所有要匹配的字符

'aabbcc'.replaceAll('b', '_');
// 相当于
'aabbcc'.replace(/b/g, '_');
// 'aa__cc'

匹配酒店房间编号

const str = '123abc456';
const regex = /(\d+)([a-z]+)(\d+)/g;

function replacer(match, p1, p2, p3, offset, string) {
  return [p1, p2, p3].join(' - ');
}

str.replaceAll(regex, replacer)
// 123 - abc - 456

参考文献

阮一峰老师的 ECMAScript 6 入门


点赞 评论 收藏 ~~ 今天的学习记录暂时到这...... ~~ 点赞 评论 收藏
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

shaoin_2

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

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

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

打赏作者

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

抵扣说明:

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

余额充值