Patrique Patrique - 4 months ago 8
Javascript Question

Take a url variable with regex

I have the following url

http://www.test.info/link/?url=http://www.site2.com


How do I get the value of the url parameter with regular expressions in javascript?

Thanks

Answer
function extractUrlValue(key, url)
{
    if (typeof(url) === 'undefined')
        url = window.location.href;
    var match = url.match('[?&]' + key + '=([^&]+)');
    return match ? match[1] : null;
}

If you're trying to match 'url' from a page the visitor is currently on you would use the method like this:

var value = extractUrlValue('url');

Otherwise you can pass a custom url, e.g.

var value = extractUrlValue('url', 'http://www.test.info/link/?url=http://www.site2.com