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
4 Answers
Reset to default 5You 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().