Chartjs-How do I break a comma separated string into new lines in tooltip callbacks afterBody?

0👍

I found my own answer:

tooltips: {
            // Disable the on-canvas tooltip
            enabled: true,
            mode: 'point',
            itemSort: function(a, b) {
                return b.datasetIndex - a.datasetIndex
            },
            callbacks: {
                afterBody: function(t, d) {
                    if(dataplayernames[t[0].index] === ""){
                        return dataplayernames[t[0].index]+'\n\rMap: '+mapname[t[0].index]+'\n\rType: '+maptype[t[0].index];
                    }
                        else{
                            let availableData = dataplayernames[t[0].index];
                            let desiredData = replaceCommaLine(availableData);
                            function replaceCommaLine(data) {
                                //convert string to array and remove whitespace
                                let dataToArray = data.split(',').map(item => item.trim());
                                //convert array to string replacing comma with new line
                                return dataToArray.join("\n");
                            }
                            return desiredData+'\n\r\n\rMap: '+mapname[t[0].index]+'\n\rType: '+maptype[t[0].index];
                        }
                }
            }
        }

Leave a comment