croft10
croft10

Reputation: 11

scrape id from url using javascript

I have the following URL:

http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.

Where bi is a identifier for the specific book. How can I extract the book id from the link?

Thanks!

Upvotes: 1

Views: 503

Answers (6)

AntonioCS
AntonioCS

Reputation: 8496

I once had the same problem.
I created a little function to help me out. Don't know where it is but I managed to recreate it:

function get(item,url) {
    if (url == undefined) 
        url = window.location.href;             

    var itemlen = item.length
    var items = url.split('?')[1].split('&');
    for (var i = 0, len = items.length;i<len;i++) {
        if (items[i].substr(0,itemlen) == item)
            return items[i].split('=')[1];  
    }

    return null;
}

So you would use it like:

get('bi');

If the url you gave was your current url, if not you could do:

get('bi','http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.')

Hope I didn't leave in any bugs :)

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57936

You can to use this regex:

var address = "http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&...";
var bi = /[\?&]bi=(\d+)/.exec(address)[1]
alert(bi)

Upvotes: 2

nickytonline
nickytonline

Reputation: 6981

Try this

var bookId
var matcher = location.search.match(/(?:[?&]bi=([^&]+))/); // Assuming window.location

if (null !== matcher) {
      bookId = matcher[1];
}

Upvotes: 0

user244671
user244671

Reputation:

address.split("bi=")[1].split("&")[0]

Upvotes: 0

miku
miku

Reputation: 188004

You can extract the book id (assumed to be only numbers) via a regular expression (and grouping).

var s = "http://www.abebooks.com/servlet/BookDetailsPL?\     
         bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.\
         %26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE\ 
         %2527S%2BGARDEN."

var re = /bi=([0-9]+)&/; // or equally: /bi=(\d+)&/

var match = re.exec(s);

match[1]; // => contains 1325819827

Upvotes: 0

Amarghosh
Amarghosh

Reputation: 59451

function getBookId()
{
    var query = document.location.split("?")[1];
    var values = query.split("&");
    for(var i = 0; i < values.length; i++)
    {
        a = values[i].split("=");
        if(a[0] === "bi")
            return a[1];
    }
    //some error occurred
    return null;
}

Upvotes: 1

Related Questions