5

If my url is http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112 using purely javascript how would I extract &client= so it would extract 123456789101112 and set it as var clientid = 123456789101112;

Yusaf Khaliq
  • 3,333
  • 11
  • 42
  • 82
  • Is it `client` or `name` GET param? – alex Oct 27 '11 at 00:49
  • If you want a more general purpose solution that can fetch any query parameter, go to this post: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript. I happen to like this answer: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript/3855394#3855394 in that post. – jfriend00 Oct 27 '11 at 00:53

4 Answers4

0
var clientid = (window.location.search.match(/[?&;]name=(\d+)/) || [])[1];

If it can contain more than numbers, use something like...

var clientid = (window.location.search.match(/[?&;]name=([^&;]+)/) || [])[1];

If the param could not be found, it will return undefined.

If you need to do this more often, you'd be better off with a generic solution.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
0

try this:

var url = "http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112"

var name = url.substring(url.indexOf('&name='), url.length)

If you don't want to user regular expression like the other answer

GregM
  • 2,634
  • 3
  • 22
  • 37
  • 1
    What if there are other GET params after `name` ? – alex Oct 27 '11 at 00:50
  • And also what if name is the first parameter? Then it won't be preceded by an `&` character. – aroth Oct 27 '11 at 00:51
  • Alex and aroth, i would do this : url.substring(url.indexOf('name='), url.indexOf(url.indexOf('name='),'&')) so it look for what is between "name=" and "&" – GregM Oct 27 '11 at 02:48
0

For a more generic/reusable solution, you can use something like:

getParameter = function(paramName, url) {
    if (! paramName) {
        return null;
    }
    if (! url) {
        url = window.location.href;
    }
    if (url.indexOf('?') == -1) {
        return null;
    }
    url = url.substring(url.indexOf('?') + 1);
    var params = url.split('&');
    for (var index = 0; index < params.length; index++) {
        var nameValue = params[index].split('=');
        if (nameValue.length == 2 && nameValue[0] == paramName) {
            return nameValue[1];
        }
    }

    return null;
};

...then just call getParameter('client');.

Example here: http://jsfiddle.net/L7hbT/3/

aroth
  • 54,026
  • 20
  • 135
  • 176
0

Not as succinct as @alex, but you could do this

var a = 'http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112';

var b = a.indexOf('name=');

var clientId = a.substring(b + 5);

alert(clientId);

Example: http://jsfiddle.net/jasongennaro/ubJe3/

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86