JavaScript - Extracting variable from string
I have the following code which works awesome for getting the variables form the URL:
HTML Code:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
document.getElementById(RefId).value = $_GET('refcode');
But it doesn't work if I use document.referrer instead of window.location
If I place window.location into a string and use the string in the function it works. If I place document.referrer in a string and use the string in the function it doesn't work.
The values of window.location is
Code:
http://site.org/Default.aspx?refcode=12345&pageId=890916
The value of document.referrer is
Code:
http://site.org/bluepage.html?refcode=12345
Any thoughts?
Re: JavaScript - Extracting variable from string
your regular expression looks for a string starting with an ampersand ("&"), and the second value you posted doesn't contain one. you'll need to modify your regular expression to either make the ampersand optional (something like: '&?', though that could bring up other potential issues), or find a better expression to represent what you need.
I know that you're trying to replace the question mark with an ampersand, but you're only doing that replacement if the first character of the string is a question mark, and the first character of the string is 'h' in both cases.
edit: also, document.referrer.search doesn't return the query string of the referrer like window.location.search does; you'll need to parse out the query string separately. I was assuming before that you were just using window.location and document.referrer, rather than window.location.search and (perhaps?) trying to use document.referrer.search -- I hadn't looked closely enough at that point.