JavaScript字符串处理,10个技巧让代码量减少30%

在 JavaScript 中,字符串处理是超级常见的操作。掌握一些高效技巧不仅能减少代码量,还能提升可读性和执行效率。以下是 10 个实用技巧,帮你精简 30% 以上的字符串处理代码:

1. 模板字符串替代拼接

  • 传统写法:用+拼接变量和字符串,多行时需要
    和+
  • 简洁写法:用反引号 包裹,变量用${}` 嵌入,支持多行
// 传统
const name = "Alice";
const age = 25;
const info = "Name: " + name + ", Age: " + age + "
From: China";

// 简洁
const info = `Name: ${name}, Age: ${age},
From: China`;

2.+操作符快速转数字

  • 传统写法:parseInt()或parseFloat()
  • 简洁写法:用+前缀直接转换(适用于纯数字字符串)
// 传统
const str = "123.45";
const num = parseFloat(str);

// 简洁
const num = +str; // 123.45

JavaScript字符串处理,10个技巧让代码量减少30%

3.includes()检查子串存在

  • 传统写法:indexOf() !== -1判断
  • 简洁写法:includes()直接返回布尔值
// 传统
const str = "hello world";
const hasWorld = str.indexOf("world") !== -1;

// 简洁
const hasWorld = str.includes("world"); // true

4.trim()系列去除空格

  • 传统写法:正则replace(/^s+|s+$/g, ”)
  • 简洁写法:trim()(首尾)、trimStart()(开头)、trimEnd()(结尾)
// 传统
const str = "  hello  ";
const trimmed = str.replace(/^s+|s+$/g, '');

// 简洁
const trimmed = str.trim(); // "hello"
const leftTrimmed = str.trimStart(); // "hello  "

JavaScript字符串处理,10个技巧让代码量减少30%

5.repeat()重复字符串

  • 传统写法:循环拼接字符串
  • 简洁写法:repeat(n)直接生成重复 n 次的字符串
// 传统
let stars = "";
for (let i = 0; i < 5; i++) {
  stars += "*";
}

// 简洁
const stars = "*".repeat(5); // "*****"

6. 一行代码反转字符串

  • 传统写法:循环遍历拼接反转
  • 简洁写法:split(”).reverse().join(”)链式调用
// 传统
function reverseStr(str) {
    let result = "";
    for (let i = str.length - 1; i >= 0; i--) {
        result += str[i];
    }
    return result;
}

// 简洁
const reverseStr = str => str.split('').reverse().join('');
reverseStr("hello"); // "olleh"

JavaScript字符串处理,10个技巧让代码量减少30%

7.startsWith()/endsWith()检查首尾

  • 传统写法:用indexOf()判断开头,lastIndexOf()判断结尾
  • 简洁写法:专用方法直接返回布尔值
const url = "https://example.com";

// 传统:检查是否以https开头
const isHttps = url.indexOf("https") === 0;

// 简洁
const isHttps = url.startsWith("https"); // true

// 传统:检查是否以.com结尾
const isCom = url.lastIndexOf(".com") === url.length - 4;

// 简洁
const isCom = url.endsWith(".com"); // true

8.replaceAll()替换所有匹配

  • 传统写法:正则加g修饰符
  • 简洁写法:replaceAll()无需写正则(ES2021+)
const str = "a,b,c,a";

// 传统:替换所有逗号为空格
const newStr = str.replace(/,/g, " ");

// 简洁
const newStr = str.replaceAll(",", " "); // "a b c a"

JavaScript字符串处理,10个技巧让代码量减少30%

9. 扩展运算符处理 Unicode 字符

  • 传统写法:split(”)可能拆分 Unicode 字符(如表情、中文)
  • 简洁写法:[…str]正确处理所有字符
const str = " 你好";

// 传统:split可能出错(部分环境下)
const arr1 = str.split(''); // 可能得到 ["�", "�", " ", "你", "好"]

// 简洁:正确拆分
const arr2 = [...str]; // ["", " ", "你", "好"]

10. 简洁的空字符串检查

  • 传统写法:判断null、undefined和空字符串
  • 简洁写法:利用逻辑运算符短路特性
const str = "";

// 传统
if (str !== null && str !== undefined && str !== "") {
  console.log("非空");
}

// 简洁:空字符串、null、undefined都会被视为false
if (str) {
  console.log("非空");
}

// 严格检查(允许空格字符串)
if (str?.trim()) {
  console.log("非空且非空格");
}

这些技巧充分利用了 JavaScript 的内置方法和语法特性,既能减少代码量,又能让逻辑更清晰。实际开发中,根据场景灵活组合使用,能显著提升编码效率。

JavaScript字符串处理,10个技巧让代码量减少30%

© 版权声明

相关文章

4 条评论

  • 头像
    The_honest 投稿者

    备注

    无记录
    回复
  • 头像
    绵绵悲雪 投稿者

    收藏了,感谢分享

    无记录
    回复
  • 头像
    懂懂 读者

    我们要求代码提交量,越多越好,精简的在中国吃不开

    无记录
    回复
  • 头像
    再吃一口蓝莓 投稿者

    哈哈你们公司牛

    无记录
    回复