Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get last part of URL

I have a series of pages where I need to get a specific code for a button. I want to put the code which is in the url into a variable with jQuery.

An example URL is www.example.com/folder/code/12345/

I want to get the number part in a variable called (siteCode)

Thanks in advance for any answers.

jquery / Pseudo code:

var siteCode;

// start function
function imageCode(){
     siteCode // equals number part of URL
     $('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
like image 211
huddds Avatar asked Jun 18 '13 10:06

huddds


Video Answer


2 Answers

I'd suggest:

var URI = 'www.example.com/folder/code/12345/',
    parts = URI.split('/'),
    lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();

JS Fiddle demo.

like image 182
David Thomas Avatar answered Oct 24 '22 18:10

David Thomas


You can use the following code to get the last part of the url.:

var value = url.substring(url.lastIndexOf('/') + 1);
like image 40
karthi Avatar answered Oct 24 '22 18:10

karthi