Xavier
Xavier

Reputation: 8362

Get last part of CSV string

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);

Upvotes: 4

Views: 1327

Answers (4)

Matt Gibson
Matt Gibson

Reputation: 14959

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().

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816840

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);

Upvotes: 3

codeandcloud
codeandcloud

Reputation: 55248

Or even

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

Upvotes: 4

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

You can use split() and pop():

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

Upvotes: 5

Related Questions