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');
}
1

5 Answers 5

14

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

var value = url.substring(url.lastIndexOf('/') + 1);
Sign up to request clarification or add additional context in comments.

1 Comment

You realise the lastIndexOf('/') occurs as the last character of the URL/string?
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.

1 Comment

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];
10
var str="url";

str.split("/")[3]

you can use split

Comments

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;
}

Comments

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");
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.