uniapp分割字符串
字符串分割方法
在UniApp中分割字符串可以使用JavaScript原生的split()方法,也可以结合正则表达式实现更灵活的分割。
使用split()方法
split()方法通过指定分隔符将字符串拆分为数组:
const str = "apple,banana,orange";
const result = str.split(",");
// 结果: ["apple", "banana", "orange"]
可以限制分割次数:
const str = "a-b-c-d";
const result = str.split("-", 2);
// 结果: ["a", "b"]
使用正则表达式分割
当分隔符较复杂时,可使用正则表达式:
const str = "apple1banana2orange";
const result = str.split(/\d/);
// 结果: ["apple", "banana", "orange"]
处理多空格分割
清除多余空格后分割:
const str = "hello world uni-app";
const result = str.split(/\s+/);
// 结果: ["hello", "world", "uni-app"]
注意事项
空字符串处理时,split()会返回包含空元素的数组:
const str = "a,,b";
const result = str.split(",");
// 结果: ["a", "", "b"]
如需过滤空值,可结合filter():
const result = str.split(",").filter(item => item);
// 结果: ["a", "b"]






