split()
方法split()
方法是最常用的将字符串分割为数组的方法。
const str = "Hello,World,JavaScript";
const arr = str.split(","); // 按逗号分割
console.log(arr); // ["Hello", "World", "JavaScript"]
// 按每个字符分割
const str2 = "hello";
const arr2 = str2.split("");
console.log(arr2); // ["h", "e", "l", "l", "o"]
...
)ES6 的扩展运算符可以将可迭代对象(如字符串)展开为数组。
const str = "hello";
const arr = [...str];
console.log(arr); // ["h", "e", "l", "l", "o"]
Array.from()
方法Array.from()
方法可以从类数组或可迭代对象创建一个新数组。
const str = "hello";
const arr = Array.from(str);
console.log(arr); // ["h", "e", "l", "l", "o"]
Object.assign()
方法虽然不常见,但也可以使用 Object.assign()
来转换:
const str = "hello";
const arr = Object.assign([], str);
console.log(arr); // ["h", "e", "l", "l", "o"]
match()
方法结合正则表达式如果需要更复杂的匹配规则,可以使用 match()
:
const str = "hello";
const arr = str.match(/./g); // 匹配所有单个字符
console.log(arr); // ["h", "e", "l", "l", "o"]
如果字符串包含 Unicode 字符(如表情符号),某些方法可能需要特别注意:
const str = "????????";
console.log([...str]); // ["????", "????"] - 正确
console.log(str.split("")); // ["�", "�", "�", "�"] - 可能不正确
对于包含复杂 Unicode 字符的字符串,推荐使用扩展运算符或 Array.from()
方法。