使用javascript从url抓取id

时间:2010-01-06 11:02:21

标签: javascript regex

我有以下网址:

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

其中bi是特定图书的标识符。 如何从链接中提取图书ID?

谢谢!

6 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以通过正则表达式(和分组)提取图书ID(假设只是数字)。

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

答案 3 :(得分:0)

address.split( “BI =”)[1] .split( “&安培;”)[0]

答案 4 :(得分:0)

试试这个

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

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

答案 5 :(得分:0)

我曾经遇到过同样的问题 我创建了一个小功能来帮助我。不知道它在哪里,但我设法重新创建它:

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

所以你会像使用它一样:

get('bi');

如果您提供的网址是您当前的网址,如果不是,您可以这样做:

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

希望我没有留下任何错误:)