Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแยกสตริงคั่นด้วย comma และ semicolon เป็นอาร์เรย์สองมิติใน JavaScript

สมมติเรามีตัวแปร "users" ที่มีสตริงข้อความนี้ โดยแต่ละ user แยกด้วย semicolon และแต่ละ attribute ของ user แยกด้วย comma:

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

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงแบบนี้และแยกเป็น multidimensional array แบบนี้:

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' ]
]