MChan
MChan

Reputation: 7162

Getting last segment of url in javascript

I am trying to use the code below to extract the last segment in a URL, but it doesn't seem to work on the URL shown below. Can someone please check the code below and tell me what I am missing here? Thanks

   var segment_str = window.location.pathname; 
   var segment_array = segment_str.split( '/' );
   var last_segment = segment_array[segment_array.length - 1];
   alert(last_segment);

URL

   http://localhost/projects/myproject/app/#/sales/invoices/224

I need to extract only 224

Upvotes: 1

Views: 328

Answers (3)

JAAulde
JAAulde

Reputation: 19550

There is a # in that URL, so "224" is part of the location's hash, not pathname.

var last_segment = window.location.hash.split('/').pop();

Upvotes: 5

Tom
Tom

Reputation: 7740

As Alan Wu said, use window.location.hash to get what's after the hash:

var segment_str = window.location.hash; 
var last_part = segment_str.substr(segment_str.lastIndexOf('/') + 1)

Will give you 224

Upvotes: 1

Alan
Alan

Reputation: 178

try window.location.hash to get the segment after the #, then split it.

Upvotes: 1

Related Questions