Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 413
Patrique Avatar asked Mar 08 '11 20:03

Patrique


3 Answers

Check out http://rubular.com to test regex:

url.match(/url=([^&]+)/)[1]
like image 95
Jordan Avatar answered Nov 17 '22 15:11

Jordan


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
like image 24
Andrew Mackrodt Avatar answered Nov 17 '22 17:11

Andrew Mackrodt


Might want to check this: http://snipplr.com/view/799/get-url-variables/ (works without regEx)

This one does use regEx: http://www.netlobo.com/url_query_string_javascript.html

function gup( name )
{
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
}


var param = gup( 'var' );
like image 3
amosrivera Avatar answered Nov 17 '22 17:11

amosrivera