Tutorial :how to extract last value in the URL using JQuery



Question:

how to extract the last value that is 1 from the following Url using jQuery...

Url : /FormBuilder/index.php/reports/export/1


Solution:1

You can use substring and lastIndexOf:

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

If the second parameter of substring is omitted, it extracts the characters to the end of the string.


Solution:2

To get it from the URL Address:

var value = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);  


Solution:3

Not really jQUery, but pure Javascript:

var a = '/test/foo/bar';  

To get the string after the last character:

var result = a.substring(a.lastIndexOf("/") + 1);  


Solution:4

Using a regex, which is just like the lastIndexOf method, but with the added benefit of being almost impossible to read/understand! ;)

var lastBit = theUrl.match(/[^\/]*$/)[0];  

There actually IS a benefit though, if you only wanted to get trailing numbers, or some other pattern you could adapt it:

// match "/abc/123", not "/abc/foo"  var lastDigits = theUrl.match(/[0-9]*$/)[0];    // match "/abc/Pie", not "/abc/123"  var matches = theUrl.match(/\/(P[^\/]*)$/);  var lastBitWhichStartsWithTheLetterP = matches ? matches[1] : null;  


Solution:5

As you can see from all of the answers JQuery isn't needed to do this.

You could split it:

var url = 'www.google.com/dir1/dir2/2';  var id = parseInt(url.split('/')[url.split('/').length - 1]);  


Solution:6

Why not use a regex?

var p = /.+\/([^\/]+)/;  var match = p.exec(str)  alert(match[1]);  


Solution:7

var arr = window.location.split("/FormBuilder/index.php/reports/export/1");  var last_val = arr[arr.length-1];  


Solution:8

Universal:

function getQueryVariable(variable)  {      var pathname = window.location.pathname.split("/");        for (i = 0; i < pathname.length; i++) {          if (pathname[i] == variable){              return pathname[i+1];          }      }    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »