1、获取字符串指定位置的值
(1)通过索引值获取
(2)charAt() 获取指定位置的字符
(3)charCodeAt() 获取指定位置字符的Unicode值
// 通过索引值获取和charAt()获取的区别:
const str = 'hello';
str.charAt(1) // 输出结果:e
str[1] // 输出结果:e
str.charAt(5) // 输出结果:''
str[5] // 输出结果:undefined
let str = "abcdefg";
console.log(str.charCodeAt(1)); // "b" --> 98
2、检索字符串是否包含特定序列
1. indexOf()
2. lastIndexOf()
3. includes()
4. startsWith()
5. endsWith()
// 最后三个都是返回true或false,并且有第二个参数
3、连接多个字符串
1. +
2. concat() 方法是专门用来拼接字符串的。该方法不会修改原有字符串,会返回连接两个或多个字符串的新字符串。
4、截取字符串
1. substr()
2. substring()
3. slice()
5、字符串转为数字
(1)parseInt()
(2)parseFloat()
6、字符串大小写转换
(1) toLowerCase()
(2)toUpperCase()
7、字符串模式匹配
replace()、match()和search()方法可以用来匹配或者替换字符。
8、移除字符串收尾空白符
trim()、trimStart()和trimEnd()这三个方法可以用于移除字符串首尾的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。
9、获取字符串本身
valueOf()和toString()方法都会返回字符串本身的值,感觉用处不大。
10、重复一个字符串
repeat() 方法返回一个新字符串,表示将原字符串重复n次:
'x'.repeat(3) // 输出结果:"xxx"
'hello'.repeat(2) // 输出结果:"hellohello"
'na'.repeat(0) // 输出结果:""
11、补齐字符串长度
padStart()和padEnd()方法用于补齐字符串的长度。如果某个字符串不够指定长度,会在头部或尾部补全。