本文总结了 JS 字符串常用知识点,含字符串语法、 13 类字符串实例方法和字符串循环与解构方法
字符串语法
特点:字符串不可更改 (immutable)
模板字面量 (Template literals)
I'm ${firstName}
字符字面量 (Character literals)
用于不会被打印但有特定作用的字符
若要打印字符字面量
console.log(String.raw `first\n second`); // first\n second
转字符串方法
| .toString() | String() | |
|---|---|---|
| 适用范围 | 若值为 null 或 undefined 则不适用 | 所有类型可转成字符串 |
| 参数 | 数字默认转 10 进制,接收基数,可转其他进制字符串表示 | / |
字符串实例方法
空、位、大、包
去空格方法
返回去空格后的原字符串拷贝
trim()trimLeft()trimRight()
字符位置获取与判断方法
获取某字符位置
可选接收第二个参数:开始搜索的位置
let str = "hello world"
indexOf("o"); // 4lastIndexOf("o"); // 7
位置顺序判断
localeCompare()
大小写转换方法
- ✅
toLowerCase() - ✅
toUpperCase() toLocaleLowerCase()toLocaleUpperCase()
包含判断方法
startsWith()endsWith()includes()
拼、拆、合、截
let str = "hello"
拼接方法
- 法一:
+ " world" // "hello world" - 法二:
.concat(" world") // "hello world"
拆合方法
let str = "hello, world"
let arr = ["hello", " world"]
- 字符串拆成数组:
str.split(",") // ["hello", " world"]
- 数组组成字符串:
arr.join(",") // "hello, world"arr.join("o") // "helloo world"
截取方法
不改变原字符串,返回字符串截取部分拷贝
- ✅
slice() substring()会将所有负值参数转换为 0substr第二个参数为返回的字符串个数
查、配、替、重、填
match()-匹配方法
接收正则表达式字符串或 RegExp 对象
search()-查找某段字符位置
接收正则表达式字符串或 RegExp 对象,返回模式第一个匹配的位置索引,如果不存在返回 -1。
replace()-替换方法
接收 1. 字符串或 RegExp 对象;2.新字符串
repeat()-重复某字符串
`let str = "na "
str.repeat(3) + "done" // "na na na done"
padStart(), padEnd() -填充方法
`let str = "333"
padStart(5, "+") // "++333"padEnd(5, "+") // "333++"
字符串循环与解构
字符串循环
for (const c of "abc") {
console.log(c);
// a
// b
// c
}
字符串按字符拆分转数组
let str = "abc"
[...str] // ["a","b","c"]