4

Say I have a CSV string:

red,yellow,green,blue

How would I programatically select blue from the string using jQuery?

The data is returned via an AJAX request from a PHP script rendering 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);
Xavier
  • 8,244
  • 18
  • 54
  • 85

4 Answers4

5

You can use split() and pop():

var lastValue = csv_Data.split(",").pop();  // "blue"
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
4

Or even

var csv_data = text.substr(text.lastIndexOf(",") + 1);
naveen
  • 53,448
  • 46
  • 161
  • 251
3

No jQuery, plain JavaScript:

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

I strongly recommend against making synchronous calls.

Reference: string.split

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

var last = text.substr(text.lastIndexOf(',') + 1);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    @naveen: I assumed the whole data will be used later on. Of course if it is not needed anymore, `pop` is just fine. – Felix Kling Aug 05 '11 at 10:50
  • all the data will be required at various steps +1 for thinking outside the box – Xavier Aug 05 '11 at 10:55
  • @Xavier: out of the box as in rabbit out of the hat? please spend some time and ask what you want clearly to avoid out of the box solutions. remember, this is also a wiki. i didnt upvote felix since it will give the wrong idea to a future visitor :) – naveen Aug 05 '11 at 11:07
0

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

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79