Plato
Plato

Reputation: 11052

How do I get the shortcode for an Instagram media item to later embed the picture?

I'd like to display Instagram photos matching particular tags on my site. I don't see a way to search for all tags over all time, so I am implementing a timer that periodically checks /tags/tag-name/media/recent for my desired tags. Then I am caching the .id attribute of any as-yet-unseen media, so I can still have access to that item if and when /tags/tag-name/media/recent no longer returns that item.

Now I am ready to embed the images on my site, but I think saving .id is mistaken. The second available embed endpoint - /p/shortcode/media - looks close. It issues a redirect to the image, which will suffice for my task, but it wants a 'shortcode', not an id.

How do I get this shortcode? There is no .shortcode attribute on the media objects returned from /tags/tag-name/media/recent. Should I use a regex to parse the .link attribute, assuming that the link will take the form http://instagr.am/p/shortcode/? Or is there a better technique to remember and later display images that match my desired tags?

Upvotes: 0

Views: 5497

Answers (4)

tmslnz
tmslnz

Reputation: 1813

This will always return the last component of a path:

'http://instagr.am/p/D/'.replace(/\/$/i, '').split("/").pop()

So http://instagr.am/p/D/ becomes D

tl;dr

  1. Remove any trailing slash (//$/i, a/b/c/a/b/c)
  2. Split by / (a/b/c[a,b,c])
  3. Get the last item in the [a,b,c] array (.pop(), [a,b,c]c)

Upvotes: 1

croban
croban

Reputation: 447

/p/([^/]+)(/.)*$ this pattern match also links like: https://instagram.com/p/6H_CiIrdKn/?taken-by=7imet4 https://instagram.com/p/6H_CiIrdKn

Upvotes: 1

Plato
Plato

Reputation: 11052

Preferring regex solution over String.split, this is what I ended up doing:

//expecting http://instagr.am/p/BWl6P/
var linkrx = /\/p\/([^\/]+)\/$/;
// find /p/, then 1 or more non-slash as capture group 1, then / and EOL
if(igPic.link.match(linkrx) !== null){
  var shortcode = igPic.link.match(linkrx)[1];
};

Upvotes: 2

krisrak
krisrak

Reputation: 12952

No other way, just use .split() from the link attribute. This will give you the shortcode:

link.split("/")[4]

Upvotes: 1

Related Questions