一、基础字符串操作
1. 字符串创建
const str1 = 'Hello World'; // 字面量创建
const str2 = String(123.45); // "123.45"
const str3 = new String('Hello').valueOf(); // 转为原始值
2. 访问字符
'cat'.charAt(1); // "a"
'cat'[1]; // "a"(ES5+)
3. 字符串不可变性
let s = 'hello';
s[0] = 'H'; // 无效
s = 'H' + s.slice(1); // 正确修改方式
二、核心字符串方法
1. 连接字符串
const result = 'Hello'.concat(' ', 'World', '!'); // "Hello World!"
2. 提取子串
'hello'.slice(1,3); // "el"(支持负数)
'hello'.substring(1,3); // "el"(自动排序参数)
3. 查找定位
'javascript'.indexOf('a'); // 1
'javascript'.lastIndexOf('a'); // 3
'Hello'.includes('ell'); // true(ES6)
4. 大小写转换
'Hello'.toLowerCase(); // "hello"
'HELLO'.toUpperCase(); // "HELLO"
'?'.toLocaleUpperCase('de-DE'); // "SS"(德语环境)
5. 空白处理
' text '.trim(); // "text"
' text '.trimStart(); // "text "
' text '.trimEnd(); // " text"
三、高级处理技巧
1. 字符串填充
'5'.padStart(3, '0'); // "005"
'25'.padEnd(4, '0'); // "2500"
2. 正则表达式集成
// 查找所有匹配
const matches = [...'test1test2'.matchAll(/t(e)(st(\d?))/g)];
// 复杂替换
'price: 100'.replace(/(\d+)/, m => `$${m*0.8}`);
3. 模板字符串高级用法
// 带标签的模板
function currency(strings, ...values) {
return strings.reduce((acc, str, i) =>
acc + str + (values[i] ? `$${values[i].toFixed(2)}` : ''), '');
}
console.log(currency`Total: ${25} + ${30}`); // "Total: $25.00 + $30.00"
// 嵌套模板
const html = `
${items.map(item => `
- ${item.name}: ${item.value}
`).join('')}
`;
四、编码与特殊处理
1. Unicode处理
''.codePointAt(0).toString(16); // "1f600"
String.fromCodePoint(0x1F600); // ""
2. Base64转换
btoa('你好'); // 报错(需先编码)
btoa(encodeURIComponent('你好')); // "JUU0JUJEJUEwJUU1JUE1JUJE"
3. URL编码
encodeURIComponent('?q=test&lang=zh'); // "%3Fq%3Dtest%26lang%3Dzh"
decodeURIComponent('%E4%BD%A0%E5%A5%BD'); // "你好"
五、性能优化技巧
1. 高效拼接
// 错误方式
let result = '';
for(let i=0; i<100000; i++) {
result += i; // 产生大量临时字符串
}
// 正确方式
const arr = [];
for(let i=0; i<100000; i++) {
arr.push(i);
}
result = arr.join('');
2. 长字符串处理
// 使用文本块处理大文本
const text = "这是一个非常长的字符串..." +
"需要分多行编写..." +
"使用加号连接更高效";
六、实用工具函数
1. 统计字符出现次数
function countOccurrences(str, char) {
return str.split(char).length - 1;
}
2. 解析查询参数
function parseQuery(query) {
return Object.fromEntries(
query.split('&').map(param => {
const [k, v] = param.split('=');
return [decodeURIComponent(k), decodeURIComponent(v || '')];
})
);
}
3. 安全HTML插入
function safeHTML(strings, ...values) {
return strings.reduce((acc, str, i) => {
let value = values[i] || '';
if (typeof value === 'string') {
value = value.replace(/&/g, '&')
.replace(//g, '>');
}
return acc + str + value;
}, '');
}
七、注意事项
- 编码陷阱
''.length; // 2(代理对字符)
[...''].length; // 4(组合emoji)
- 正则性能
// 避免在循环中重复创建正则
const regex = /test/g; // 预先编译
while((match = regex.exec(str)) !== null) {
// 处理匹配
}
- 换行符统一
function normalizeNewlines(str) {
return str.replace(/\r\n?/g, '\n');
}
- 多语言处理
'?'.localeCompare('z', 'de'); // 德语排序返回负数
'?'.localeCompare('z', 'sv'); // 瑞典语返回正数
八、ES2022+ 新特性
1..at()方法
'abc'.at(-1); // 'c'
2. 正则匹配索引
const match = 'abc'.match(/b/d);
console.log(match.indices[0]); // [1, 2]
3..replaceAll()方法
'a-b-c'.replaceAll('-', ' '); // "a b c"
本文涵盖了从基础操作到高级技巧的完整字符串处理方法,结合最新ES规范,适用于现代JavaScript开发的各种场景。建议根据具体需求选择合适的方法,并注意处理Unicode和多语言环境下的特殊情况。