| 查找与判断 |
includes(substr) |
判断字符串是否包含子串,返回布尔值。 |
'Hello'.includes('e') // true |
|
indexOf(substr) |
返回子串首次出现的索引,未找到返回 -1。 |
'Hello'.indexOf('l') // 2 |
|
lastIndexOf(substr) |
返回子串最后一次出现的索引,未找到返回 -1。 |
'Hello'.lastIndexOf('l') // 3 |
|
startsWith(substr) |
判断字符串是否以子串开头,返回布尔值。 |
'Hello'.startsWith('He') // true |
|
endsWith(substr) |
判断字符串是否以子串结尾,返回布尔值。 |
'Hello'.endsWith('lo') // true |
|
search(regexp) |
使用正则表达式搜索,返回首次匹配的索引。 |
'Hello'.search(/[lo]/) // 2 |
|
match(regexp) |
使用正则表达式搜索,返回匹配结果的数组。 |
'Hello'.match(/l/g) // ['l', 'l'] |
| 截取与分割 |
slice(start, end) |
提取子串,支持负数索引(从末尾开始)。 |
'Hello'.slice(1, 4) // 'ell' |
|
substring(start, end) |
提取子串,但不支持负数索引。 |
'Hello'.substring(1, 4) // 'ell' |
|
substr(start, length) |
⚠️ 从起点提取指定长度的子串(已弃用)。 |
'Hello'.substr(1, 3) // 'ell' |
|
split(separator) |
根据分隔符将字符串分割成数组。 |
'a,b,c'.split(',') // ['a','b','c'] |
| 修改与替换 |
replace(searchVal, newVal) |
替换第一个匹配的子串或正则匹配项。 |
'Hi!'.replace('!', '?') // 'Hi?' |
|
replaceAll(searchVal, newVal) |
替换所有匹配的子串。 |
'aabb'.replaceAll('b', 'c') // 'aacc' |
|
concat(str1, str2, ...) |
连接多个字符串,返回新字符串。 |
'Hello'.concat(' ', 'World') // 'Hello World' |
|
repeat(count) |
将字符串重复指定次数后返回新字符串。 |
'Ha'.repeat(3) // 'HaHaHa' |
|
trim() |
去除字符串两端的空白字符。 |
' a '.trim() // 'a' |
|
trimStart()/trimEnd() |
分别去除开头或结尾的空白字符。 |
' a '.trimStart() // 'a ' |
| 大小写转换 |
toLowerCase() |
将字符串转换为小写。 |
'Hello'.toLowerCase() // 'hello' |
|
toUpperCase() |
将字符串转换为大写。 |
'Hello'.toUpperCase() // 'HELLO' |
| 字符与编码 |
charAt(index) |
返回指定位置的字符。 |
'Hello'.charAt(1) // 'e' |
|
charCodeAt(index) |
返回指定位置字符的 UTF-16 编码。 |
'A'.charCodeAt(0) // 65 |
|
String.fromCharCode(num) |
将 UTF-16 编码转换回字符(静态方法)。 |
String.fromCharCode(65) // 'A' |
| 填充与格式化 |
padStart(len, padStr) |
在开头填充字符,直到字符串达到指定长度。 |
'5'.padStart(3, '0') // '005' |
|
padEnd(len, padStr) |
在结尾填充字符,直到字符串达到指定长度。 |
'5'.padEnd(3, '0') // '500' |