JavaScript字符串处理
1. 模板字符串替代字符串拼接
// 传统方式
const greeting = 'Hello, ' + user.name + '! You have ' + user.notifications + ' notifications.';
// 模板字符串
const greeting = `Hello, ${user.name}! You have ${user.notifications} notifications.`;
模板字符串不仅代码更简洁,而且可读性更强,尤其是在处理多行文本时。
2. 解构赋值提取字符串
// 传统方式
const firstChar = str.charAt(0);
const lastChar = str.charAt(str.length - 1);
// 解构赋值
const [firstChar, ...rest] = str;
const lastChar = str.slice(-1);
解构赋值不仅可以用于数组,还可以用于字符串,使得字符提取变得更加简洁。
3. 使用String.prototype.includes代替indexOf
// 传统方式
if (str.indexOf('JavaScript') !== -1) {
// 字符串包含"JavaScript"
}
// 使用includes
if (str.includes('JavaScript')) {
// 字符串包含"JavaScript"
}
includes
方法更直观,意图更明确,减少了不必要的比较操作。
4. 使用String.prototype.startsWith和endsWith
//传统方式
if (str.indexOf('Hello') === 0) {
// 字符串以 "Hello" 开头
}
if (str.lastIndexOf('World') === str.length - 'World'.length) {
// 字符串以 "World" 结尾
}
//使用 startsWith 和 endsWith
if (str.startsWith('Hello')) {
// 字符串以 "Hello" 开头
}
if (str.endsWith('World')) {
// 字符串以 "World" 结尾
}
这些方法使代码更加语义化,减少了错误的可能性。
5. 字符串填充与对齐
//使用 padStart 和 padEnd
const paddedStart = '5'.padStart(3, '0'); // "005"
const paddedEnd = '5'.padEnd(3, '0'); // "500"
padStart
和padEnd
方法可以轻松实现字符串填充,适用于格式化数字、创建表格等场景。
6. 使用replace与正则表达式
//传统方式
let str = 'foo bar baz';
str = str.replace('foo', 'qux');
str = str.replace('bar', 'quux');
//链式调用
const str = 'foo bar baz'
.replace(/foo/, 'qux')
.replace(/bar/, 'quux');
7. 使用String.prototype.trim系列方法
//传统方式
const trimmed = str.replace(/^\s+|\s+$/g, '');
//使用 trim
const trimmed = str.trim();
8. 使用String.prototype.repeat
//传统方式
function createSeparator(length) {
let separator = '';
for (let i = 0; i < length; i++) {
separator += '-';
}
return separator;
}
//使用 repeat
const separator = '-'.repeat(10); // "----------"
9. 使用可选链操作符处理嵌套对象属性
//传统方式
const name = user && user.profile && user.profile.name;
//使用可选链
const name = user?.profile?.name;
10. 使用字符串插值替代条件拼接
// 传统方式
let message = 'You have ' + count + ' item';
if (count !== 1) {
message += 's';
}
message += ' in your cart.';
// 使用字符串插值
const message = `You have ${count} item${count !== 1 ? 's' : ''} in your cart.`;