Split Comma and Semicolon Separated String into Two-Dimensional Array in JavaScript



Let's say we have a variable “users” that contains the following string of text where each user is separated by a semicolon and each attribute of each users is separated by a comma −

const users = 'Bob,1234,[email protected];Mark,5678,[email protected]';

We are required to write a JavaScript function that takes in one such string and splits this into a multidimensional array that looks like this −

const arr = [
   ['Bob', 1234, '[email protected]'],
   ['Mark', 5678, '[email protected]']
];

Example

The code for this will be −

const users = 'Bob,1234,[email protected];Mark,5678,[email protected]';
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));

Output

And the output in the console will be:
[
   [ 'Bob', '1234', '[email protected]' ],
   [ 'Mark', '5678', '[email protected]' ]
]
Updated on: 2020-11-21T10:15:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements