0

I have this code:

var guestid = $(this).attr('href');

This gets me the current url, at the end of the url it has ?lid=8

How can I extract the 8 from that url? I tried this:

var guestid = $(this).attr('href').match(/\?lid=([0-9]+)$/);

But it returns null.

John
  • 9,840
  • 26
  • 91
  • 137
  • 1
    Similar thread: http://stackoverflow.com/questions/872217/jquery-how-to-extract-value-from-href-tag – Heikki Jan 03 '11 at 01:22
  • @Heikki Thank you! That gave me what I needed, var guestid = $(this).attr("href").match(/lid=([0-9]+)/)[1]; – John Jan 03 '11 at 01:34

3 Answers3

1
$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

// вызов: передаём параметр, который хотим достать из url'а
//(translation) Call: passing a parameter that we want to get out of
$.urlParam('Id');

source

jonsca
  • 10,218
  • 26
  • 54
  • 62
1

You have to use $(location).attr('href'); to get url using jquery or use window.location.pathname;. Your regular expression is correct

EDIT

var mRegexp = /\?lid=([0-9]+)$/; 
var match = mRegexp.exec($(this).attr('href'));
alert(match[1]);
Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
  • The code is used from a click action. When I do an alert on var guestid = $(this).attr('href'); it gives me back the url just fine. I just need to know how to extract the id from the url string guestid contains. – John Jan 03 '11 at 01:16
  • If I do this, var guestid = $(this).attr('href').match(/\?lid=[0-9]+$/); not surrounding the number with () then it gives me ?lid=8 as the value. So what am I doing wrong to just extra the number? – John Jan 03 '11 at 01:21
  • use `regex.exec`. `var mRegexp = /\?lid=([0-9]+)$/; var match = mRegexp.exec(myString);lert(match[1]); ` – Teja Kantamneni Jan 03 '11 at 01:23
0

If that's the only thing in the querystring, do this:

var guestid = this.search.split('=')[1];

...and you've got it.

Example: http://jsfiddle.net/zzhPj/

No need for a regex.

user113716
  • 318,772
  • 63
  • 451
  • 440