ManuKaracho
ManuKaracho

Reputation: 1218

How can I get the last element of a string array with one line of code?

Right now, I get the last part of an URL to exclude the filename like this:

attachmentFileName = attachmentLink.split("/");
attachmentFileName = attachmentFileName[attachmentFileName.length-1];

it feels, as if I could do that in one statement only, but I can't figure out how. Not a big deal, but i think it can be done more elegantly.

Upvotes: 1

Views: 454

Answers (2)

madox2
madox2

Reputation: 51861

You can use Array.prototype.pop() method to retrieve last element of your splitted array:

attachmentFileName = attachmentLink.split("/").pop();

Upvotes: 3

Kishore Indraganti
Kishore Indraganti

Reputation: 1322

Please give a try to below code

attachmentFileName = attachmentLink.substring(attachmentLink.lastIndexOf("/")+1,attachmentLink.length);

Upvotes: 1

Related Questions