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 that is in the url in a variable with jQuery.

Example URL: www.example.com/folder/code/12345/

I want to get the numerical 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'); } 
+8
javascript jquery html url get
source share
5 answers
 var str="url"; str.split("/")[3] 

you can use split

+8
source share

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

 var value = url.substring(url.lastIndexOf('/') + 1); 
+11
source share

I would suggest:

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

JS Fiddle demo .

+10
source share

There is one better way to take the last part of the URL, as shown below, which is commonly used in a real implementation.

There are several loopholes in the previously given answer:

1. Note that if there is a URL, for example www.example.com/folder/code/12345 (Without the '/' forward slash), then none of the above codes will work on hold.

2. Notice if the hierarchy of folders increases, like www.example.com/folder/sub-folder/sub-sub-folder/code/12345

 $(function () { siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/'); }); var getLastPartOfUrl =function($url) { var url = $url; var urlsplit = url.split("/"); var lastpart = urlsplit[urlsplit.length-1]; if(lastpart==='') { lastpart = urlsplit[urlsplit.length-2]; } return lastpart; } 
+3
source share

Also try using regex

 var url = "www.example.com/folder/code/12345"; var checkExt = /\d$/i.test(url); if (checkExt) { alert("Yup its a numeric"); } else { alert("Nope"); } 
+1
source share

All Articles