tags:

views:

609

answers:

6

Hi,

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

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

Thanks in advance..

+2  A: 

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.

CMS
5 seconds! You sneaky Guatemalan :)
Andy Gaskell
@Andy: LOL exactly 5 sec, that was really close!
CMS
A: 
var arr = window.location.split("/FormBuilder/index.php/reports/export/1");
var last_val = arr[arr.length-1];
Rafal Ziolkowski
Split requires a parameter. http://www.w3schools.com/jsref/jsref_split.asp
FractalizeR
A: 

Why not use a regex?

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

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);
Carlos
A: 

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]);
Brian
+1  A: 

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