10

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

5 Answers 5

20
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
Sign up to request clarification or add additional context in comments.

Comments

15

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

url.match(/url=([^&]+)/)[1]

2 Comments

As in the RFC: tools.ietf.org/html/rfc3986#section-3.3 The semicolon(';') character can also be used to delimit parameters, So I think the regex pattern would be like url.match(/url=([^&;]+)/)[1]
This will also match something like example.com/notthisurl=match&url=wontmatch being it an unexpected behavior. To fix this I can imagine a regex like this one url.match(/(\?|&)url=([^&]+)/)[2]
3

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' );

Comments

3

Well, firstly, is that the whole query string? If so, all you need to do is split on the =:

url.split('=')[1];

Otherwise, you might want to use Jordan's Regex.

Comments

0

On the answer code:

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

If key is a last parameter in URL and after that there is an anchor - it enter code herewill return value#anchor as a value. # in regexp '[?&]' + key + '=([^&#]+)' will prevent that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.