如何将由逗号和分号分隔的字符串拆分为 JavaScript 中的二维数组?


假设我们有一个包含以下文本字符串的变量“users”,其中以分号分隔各个用户,以逗号分隔各个用户的各个属性 −

const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';

我们需要编写一个 JavaScript 函数,接收这样一个字符串,将其拆分为一个看起来像下面的多维数组 −

const arr = [
   ['Bob', 1234, 'Bob@example.com'],
   ['Mark', 5678, 'Mark@example.com']
];

例如

代码如下 −

const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';
const splitByPunctuations = (str = '') => {
   let res = [];
   res = str.split(';');
   for(let i = 0; i < res.length; i++){
      res[i] = res[i].split(',');
   };
   return res;
};
console.log(splitByPunctuations(users));

输出

And the output in the console will be:
[
   [ 'Bob', '1234', 'Bob@example.com' ],
   [ 'Mark', '5678', 'Mark@example.com' ]
]

更新日期:2020 年 11 月 21 日

1 万次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.