1. 首页
  2. Java

离谱,split方法的设计缺陷居然导致了生产bug!

一、split方法

1.语法

split() 用于将字符串按照指定分隔符分割成数组

string.split(separator, limit)

separator(可选):指定分隔符,可以是字符串或正则表达式。如果省略,则返回整个字符串作为数组。

limit(可选):整数,限制返回的数组的最大长度。如果超过限制,多余的部分将被忽略。

2.基本用法

使用字符串作为分隔符

const text = "苹果,华为,小米";
const result = text.split(","); 
console.log(result); 
// 输出: ['苹果', '华为', '小米']

使用正则表达式作为分隔符

const text = "苹果,华为,小米";
const result = text.split(/[,; ]+/); // 匹配逗号、分号或空格
console.log(result); 
// 输出: ['苹果', '华为', '小米']

使用限制参数

const text = "苹果,华为,小米";
const result = text.split(",", 2); 
console.log(result); 
// 输出: ['苹果', '华为'] (限制数组长度为 2)

没有找到分隔符

const text = "hello";
const result = text.split(","); 
console.log(result); 
// 输出: ['hello'] (原字符串直接返回)

二、split方法常见踩坑点

1.空字符串的分割

const result = "".split(",");
console.log(result);
// 输出: [''] (非空数组,包含一个空字符串)

原因:

空字符串没有内容,split() 默认返回一个数组,包含原始字符串。

解决方案:

const result = "".split(",").filter(Boolean);
console.log(result);
// 输出: [] (使用 filter 移除空字符串)

2.多余分隔符

const text = ",,苹果,,华为,,";
const result = text.split(",");
console.log(result);
// 输出: ['', '', '苹果', '', '华为', '', '']

原因:

连续的分隔符会在数组中插入空字符串。

解决方案:

const text = ",,苹果,,华为,,";
const result = text.split(",").filter(Boolean);
console.log(result);
// 输出: ['苹果','华为']

filter(Boolean) 是一个非常常用的技巧,用于过滤掉数组中的假值。

3.分割 Unicode 字符

const text = "👍😊👨‍👩‍👦";
const result = text.split('');
console.log(result);
// 输出: ['👍', '😊', '👨', '‍', '👩', '‍', '👦']

原因:

split("") 按字节分割,无法正确识别组合型字符。

解决方案:

const text = "👍😊👨‍👩‍👦";
const result = Array.from(text);
console.log(result);
// 输出: ['👍', '😊', '👨‍👩‍👦'] (完整分割)



TOP