ES6 学习笔记之字符串拓展
- 2020 年 1 月 5 日
- 笔记
字符换相关的拓展在书中有非常详细的介绍,我这里仅记录一些可能会用到的函数或方法,以备后用。
正确打印一个字符串序列
var s = 'a'; for (let ch of s) { console.log(ch.codePointAt(0).toString(16)); }
以上由于 “ 占用 4 个字符,如果用传统的 charCodeAt 或者 charAt 都无法正常读取,所以需要用到新的方法 codePointAt()
。
判断一个字符是 4 字节还是 2 字节
function is32Bit(c) { return c.codePointAt(0) > 0xFFFF; } console.log(is32Bit('')); console.log(is32Bit('a'));
for..of 遍历字符串
var text = String.fromCodePoint(0x20BB7); for (let i = 0; i < text.length; i++) { // 无法正常打印文字,识别为两个字节,被截断 console.log(text[i]); } for (let ch of text) { // 正确打印,能正常识别四个字节的字符 console.log(ch); }
子字符串查找函数
var str = "hello world"; console.log(str.includes('ello')); console.log(str.startsWith('hello')); console.log(str.endsWith('world'));
- includes 判断字符串中是否包含某个子字符串。
- startsWith 判断字符串开头是否包含某子字符串。
- endWith 判断字符串结尾是否包含某子字符串。
字符串长度填充补全
console.log('0000008E'.padStart(10, '0x')); console.log('x'.padEnd(10, '0'));
可以让某字符串按规定长度显示,如不够指定长度则用参数 2 补全。
字符串与变量拼接(模板字符串)
ES5 字符串拼接使用加号:
for (var i = 0; i < 100; i++) { console.log('活到 ' + i + ' 岁'); }
在 ES6 中则相对简洁化了,将原来的引号换成了反引号,变量用 ${}
括起来,中间不再需要加号。
for (let i = 0; i < 100; i++) { console.log(`活到 ${i} 岁`); }
模板字符串还有非常多的规则,详情请参考书中资料。