leonard vertighel leonard vertighel - 5 months ago 18
JSON Question

Javascript remove leading and trailing spaces from multiline string

How can I convert this text

data=`ID ra dec V VR MJD
100 30.1 +15 7.00 -10 2450000.1234
200 30.2 +16 12.226 -5.124 2450000.2345
300 30.3 +17 13.022 12.777 2450000.3456


400 30.4 +18 14.880 13.666 2450000.6789
500 30.5 +19 12.892 -1.835 2450001
600 30.6 +20 17.587 15.340 2450002.123
700 30.7 +21 13.984 13.903 2450000.123456
800 30.8 +22 20.00 10.000 2450003.0 `


i.e an imported text with multiple lines and columns separated by spaces and tabs, into this

ID,ra,dec,V,VR,MJD
100,30.1,+15,7.00,-10,2450000.1234
200,30.2,+16,12.226,-5.124,2450000.2345
300,30.3,+17,13.022,12.777,2450000.3456


400,30.4,+18,14.880,13.666,2450000.6789
500,30.5,+19,12.892,-1.835,2450001
600,30.6,+20,17.587,15.340,2450002.123
700,30.7,+21,13.984,13.903,2450000.123456
800,30.8,+22,20.00,10.000,2450003.0


Unfortunately,


  • this regex
    data=data.replace(/^\s+|\s+$/g,'').replace(/[\t \r]+/g,',');
    only works with the first line,

  • this one
    data.replace(/[^\S\r\n]+$/gm, "").replace(/[\t \r]+/g,',');

    is ok, but only for for for traling.



Extra: How can I transform it to a
json
which separate the two blocks into two datasets such as
[[{id:..., ra:...},{},{}],[{id:..., ra:...},{},{}]]

Answer

The string conversion might be easier with split/join and trim:

data
    .split(/\r?\n/)
    .map(row => row.trim().split(/\s+/).join(','))
    .join('\n')

The extra credit is a little more involved. :)

const rows = data.split(/\r?\n/).map(row => row.trim().split(/\s+/).join(','));
const keys = rows.shift().split(',');
const chunks = rows.join("\n").split(/\n{2,}/);

const output = chunks .map(chunk => chunk.split("\n").map(
    row => row.split(',').reduce((obj, v, i) => {
        obj[keys[i]] = v;
        return obj;
    }, {})
));
Comments