Dynamically Split a table cell into multiple columns depending on the comma

I have the following HTML Table displays data from the database.
The cell data use btn btn-info Bootstrap Button element to highlight the Location Visited Column.

Current Table:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>

 <table class="table">
                      <th scope="col">#</th>
                      <th scope="col">Name</th>
                      <th scope="col">Surname</th>
                      <th scope="col">Location Visited</th>
                      <th scope="col">Date</th>
                      <th scope="row">1</th>
                          <span class="btn btn-info">
                                R-Block, S-Block, Audit-Block
                        <td>June, 24, 2012</td>
                      <th scope="row">2</th>
                          <span class="btn btn-info">
                               T-Block, S-Block, Finance-Block
                         <td>January, 14, 2012</td>
                      <th scope="row">3</th>
                          <span class="btn btn-info">
                                R-Block, H-Block,Admin-Block
                         <td>December, 04, 2012</td>

I want the Cell to always split data whenever a comma is loaded in the cell.

I Have tried using Colspan but I want the CELL Data to split into multiple columns automatically whenever a comma is present. e.g: if the cell has 2 commas columns, there must be two columns/(blocks), and if the cell has 3 commas the column/(blocks) has to be 3 as well.

Desired Output.

enter image description here

32 thoughts on “Dynamically Split a table cell into multiple columns depending on the comma”

  1. You could split the string into an array with

    let newArray = string.split(",");

    And then create a forEach(), like:

    newArray.forEach( (item) => {
     let column = document.createElement('td');
     let block = document.createElement('span');
     block.setAttribute('class', 'btn btn-info');
     block.innetHTML = item;

Leave a Comment