最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get last part of CSV string - Stack Overflow

programmeradmin7浏览0评论

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

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);
Share Improve this question edited Aug 5, 2011 at 10:55 Xavier asked Aug 5, 2011 at 10:42 XavierXavier 8,36218 gold badges56 silver badges85 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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

  1. 暂无评论