开发者

Get last part of CSV string

Say I have a CSV string开发者_C百科:

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


You can use split() and pop():

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


Or even

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜