JS字符串常用方法
JavaScript 中数组(Array)和字符串(String)的内置方法非常丰富,掌握常用的高效函数能大幅提升开发效率。以下是按 “高频使用” 和 “实用场景” 分类的精选函数:
1. 截取与分割
slice(start, end)
截取子串(类似数组slice,支持负数索引)。javascript'hello'.slice(1,4); // 'ell'(从索引1到3) 'hello'.slice(-3); // 'llo'(从倒数第3位到结尾)substring(start, end)
类似slice,但不支持负数索引(start>end会自动交换)。javascript'hello'.substring(4,1); // 'ell'(自动交换为 1-4)split(separator, limit)
按分隔符分割为数组(limit限制返回长度)。javascript'a,b,c'.split(','); // ['a','b','c'] 'hello'.split('', 3); // ['h','e','l'](按字符分割,取前3个)
2. 查找与替换
indexOf(searchValue, start)/lastIndexOf(searchValue)indexOf:从start开始找第一个匹配的索引(找不到返回 -1)。lastIndexOf:从末尾找最后一个匹配的索引。
javascript'abac'.indexOf('a'); // 0 'abac'.lastIndexOf('a'); // 2includes(searchValue)
判断字符串是否包含子串(返回布尔值,ES6+)。javascript'hello'.includes('ll'); // truestartsWith(searchValue, start)/endsWith(searchValue, length)startsWith:是否以子串开头(start为起始位置)。endsWith:是否以子串结尾(length为字符串长度,默认自身长度)。
javascript'hello'.startsWith('he'); // true 'hello'.endsWith('lo'); // truereplace(searchValue, replacement)
替换子串(默认只替换第一个,用正则/g全局替换)。javascript'aabb'.replace('a', 'x'); // 'xabb' 'aabb'.replace(/a/g, 'x'); // 'xxbb'
3. 转换与处理
toUpperCase()/toLowerCase()
转换为全大写/全小写。javascript'Hello'.toUpperCase(); // 'HELLO'trim()/trimStart()/trimEnd()
去除首尾空格 / 开头空格 / 结尾空格。javascript' hello '.trim(); // 'hello'padStart(length, padStr)/padEnd(length, padStr)
在开头/结尾补全字符串至指定长度(常用于格式化,如补零)。javascript'5'.padStart(2, '0'); // '05'(补全为2位,不足用0填充) 'hi'.padEnd(4, '!'); // 'hi!!'repeat(n)
重复字符串n次。javascript'ab'.repeat(3); // 'ababab'
数组与字符串互通技巧
字符串 → 数组:
- 单个字符:
[...str]或str.split('')javascript[...'hello']; // ['h','e','l','l','o'] - 按分隔符:
str.split(separator)
- 单个字符:
数组 → 字符串:
arr.join('')(无分隔符拼接)javascript['h','i'].join(''); // 'hi'
总结
- 字符串核心场景:截取分割(
slice/split)、查找替换(includes/replace)、格式化(padStart/trim)。
根据具体需求选择合适的方法,避免过度使用函数式方法(如 forEach 替代 for 循环可能影响性能),复杂操作优先考虑 reduce 或原生语法。