I am working on a case where I want to convert the data from string to arrays based on delimiters. In the below example I have |
as a delimiter and I want to convert it into a array of values.
It works fine in ideal case. But in case if there is consecutive delimiters (As you can see in 3rd line v3|v3||v3|v3
). I want to add null
or empty string
to to the array.
How can I add null value when I find two consecutive delimiters.
const data = `
h1|h2|h3|h4|h5
v1|v1|v1|v1|v1
v2|v2|v2|v2|v2
v3|v3||v3|v3
`;
const lines = data.trim().split(/\n/g);
const result = lines.map(line => line.trim().split(/\|+/g));
console.log(result);