Reputation: 1001
I recently was introduced to the world of APIs, and I'm trying to wrap my head around it a bit more, so thank you all in advance!
I have the following JSON data:
[
{
"description": "Batman does.\n\nBatman vs. The Penguin (with Patton Oswalt)",
"updated_time": "2016-03-29T16:35:00+0000",
}
]
Doing something like
var var1 = array.[0]description
will store var1 as the whole description.
I use Javascript (JQuery specifically). I want to get only the description before the \n\
i.e Batman does., and store it in a variable.
Upvotes: 2
Views: 64
Reputation: 11
Try the code below,
var desc = (data[0].description.match(/[^\n]+/) || [''])[0];
Upvotes: -1
Reputation: 26861
Another way of achieving this is to substring()
from 0 to the indexOf()
\n
:
var desc = data[0].description.substring(0, data[0].description.indexOf('\n') );
Although, the answer provided by Phil looks easier to read/understand for this case.
Upvotes: 1
Reputation: 164764
Split on the newline and take the first array item, eg
var desc = data[0].description.split('\n')[0];
Parse the date string into a Date
instance. Seeing as your string is ISO 8601 compliant, you can simply use the Date
constructor...
var d = new Date(data[0].updated_time);
See formatting options here ~ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter
Upvotes: 5