9

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');
}
AurA
  • 12,135
  • 7
  • 46
  • 63
huddds
  • 1,045
  • 6
  • 27
  • 47

5 Answers5

14

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

var value = url.substring(url.lastIndexOf('/') + 1);
Kees Sonnema
  • 5,759
  • 6
  • 51
  • 106
karthi
  • 889
  • 12
  • 24
11

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.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Using `.pop()` confuses things as it's destructive and changes the `parts[]` array. If your URI does not have a trailing slash, this fails to return '12345' and instead returns 'code'. Using this version is more straight-forward: `lastPart = parts[parts.length-1] !== '' ? parts[parts.length-1] : parts[parts.length-2];` – atwixtor Feb 09 '17 at 18:21
10
var str="url";

str.split("/")[3]

you can use split

PSR
  • 39,804
  • 41
  • 111
  • 151
3

There is one best way to take last part of URL is like following which generally has been used in real implementation.

There are Some loopholes in previously given answer was:

1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.

2.Consider if folder hierarchy 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;
}
Husen
  • 35
  • 4
1

Also try using

var url = "www.example.com/folder/code/12345";
  var checkExt = /\d$/i.test(url);
  if (checkExt) {
      alert("Yup its a numeric");
  } else {
      alert("Nope");
  }
Praveen
  • 55,303
  • 33
  • 133
  • 164