微信小程序支持ES6字符串拓展

1、includes(), startsWith(), endsWith()

includes(n)检查字符串中是否存在指定的字符串,返回布尔值,n代表检索的起始位置,n可以不传

startsWith(n)判断字符串是否已某个字符串开头,返回布尔值,n代表检索的起始位置,n可以不传

endsWith(n)判断字符串是否以某个字符串结尾,返回布尔值,n代表检索的起始位置,n可以不传,这里要注意n的使用

let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

2、repeat(n)

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

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

如果是小数,会被取整,小数点后被忽略

3、codePointAt

使用场景比较少,能支持4个字节存储的字符,js默认是给字符分配两个字节的存储大小,使用方法如下:

let s = '?a';
s.codePointAt(0)

该方法默认返回的是十进制的值,要返回其它进制的值可以使用toString方法转换,如下转为16进制值:

let s = '?a';
s.codePointAt(0).toString(16) // "20bb7"
s.codePointAt(2).toString(16) // "61"

这里要获取a的code值,索引要传2,使用不是很方便,可以用for...of方法遍历所有的code值:

let s = '?a';
for (let ch of s) {
  console.log(ch.codePointAt(0).toString(16));
}
// 20bb7
// 61

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

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

4、String.fromCodePoint()

与codePointAt()作用相反,将code值转为字符

String.fromCodePoint(0x20BB7)
// "?"
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y'
// true

5、normalize(ios8/ios9不支持该方法)

统一字符表示,不常用

'\u01D1'.normalize() === '\u004F\u030C'.normalize()
// true

参考链接

猜你喜欢

转载自blog.csdn.net/yann02/article/details/87430909