JS:String 方法大总结(至 ES6)

文章目录

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
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值