Get the last part of a CSV line

Say I have a CSV line:

red,yellow,green,blue 

How would I programmatically select blue from a string using jQuery?

Data is returned using an AJAX request from a PHP script that displays a CSV file.

 var csv_Data; $.ajax({ type: 'GET', url: 'server.php', async: false, data: null, success: function(text) { csv_Data = text; } }); console.log(csv_Data); 
+4
source share
4 answers

No jQuery, plain javascript:

 var csv_Data = text.split(','); var last = csv_Data[csv_Data.length - 1]; 

I highly recommend making synchronous calls.

Link: string.split

Update: If you really want to get the last value, you can use lastIndexOf [docs] and
substr [docs] :

 var last = text.substr(text.lastIndexOf(',') + 1); 
+3
source

You can use split () and pop () :

 var lastValue = csv_Data.split(",").pop(); // "blue" 
+4
source

Or even

 var csv_data = text.substr(text.lastIndexOf(",") + 1); 
+3
source

You can use the jQuery CSV plugin according to the instructions here . However, the CSV format usually has quotes around the values. It would be easier to send data in JSON format from a PHP file using json_encode ().

0
source

All Articles