String | 方法名 |
---|---|
字符方法 | charAt、charCodeAt、codePointAt、normalize |
字符串拼接方法 | concat、slice、substr、substring |
字符串位置方法 | indexOf、lastIndexOf、includes、startsWith、endsWith |
去除首尾空格 | trim、trimStart、trimEnd |
字符串重复 | repeat |
字符串补全 | padStart、padEnd |
字符串的大小写转换 | toLowerCase、toUpperCase、toLocaleLowerCase、toLocaleUpperCase |
字符串模式匹配方法 | match、matchAll、search、replace、split |
比较字符串 | localeCompare |
编码转字符串 | fromCharCode、fromCodePoint |
模板字符串处理 | raw |
标红为 ES6 方法
问题记录
判断字符字节数
测试一个字符由两个字节还是由四个字节组成的最简单方法
function is32Bit(c) {
return c.codePointAt(0) > 0xFFFF;
}
is32Bit("𠮷") // true
is32Bit("a") // false
字符方法
String.prototype.charAt(index)
从一个字符串中返回指定的字符
String.prototype.charCodeAt(index)
参数同上,返回的是字符编码
String.prototype.codePointAt(pos)
正确处理 4 个字节储存的字符
String.prototype.normalize([form])
将字符的不同表示方法统一为同样的形式
- 许多欧洲语言有语调符号和重音符号,unicode 表示方法有两种,一种是直接提供带重音符号的字符,另一种是提供合成符号,这两种方法表示,js 不能识别
- form 四种 Unicode 正规形式
字符串操作方法
String.prototype.concat(string2, string3[, …, stringN])
拼接字符串,返回拼接得到的新字符串。可接收任意多个参数。实践中拼接字符串用得比较多的是"+"。
String.prototype.slice(beginIndex[, endIndex])、substr(start[, length])、substring(indexStart[, indexEnd])
截取子字符串,均不会影响原字符串。接收一或二个参数。
- 第一个参数指定子字符串位置
- slice() 和 substr