-1

How would I get the value 'b' or the value 'bluebell' from the following url:

www.example.com/en/park/wildlife-z/?item=bluebell&loc=b

I know you can use location.search but that returns the last part of the url??

edit:

This is what I used:

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

alert(getParameterByName("param1","www.example.com/test?param1=1&param2=2"));
Rob Morris
  • 525
  • 1
  • 6
  • 20

3 Answers3

0

Though this has already been asked multiple times, I offer up the solution I came up with a good while back. I wrote a jquery extension to do it:

$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name] || '';
    }
});

You can then use it as follows (decodeUri is not necessary, but it's handy if the querystring is URIEncoded):

decodeURI($.getUrlVar("Title"))

Disclaimer: I did originally get this from a blog or from this site (and modify it), but I can't remember where. Not meaning to take credit from anyone.

Spikeh
  • 3,540
  • 4
  • 24
  • 49
0

You could use php.js and do it as in PHP with parse_url and parse_str functions:

var url = 'www.example.com/en/park/wildlife-z/?loc=b&str=test';

var query_obj = {};
parse_str( parse_url( url, 'PHP_URL_QUERY' ), query_obj );

// query_obj = {"loc":"b","str":"test"}

And the same result gives the example below ( without the use of additional scripts ):

var arr = url.slice( url.indexOf( '?' ) + 1 ).split( '&' );

var query_obj = {};
$.each( arr, function( i, value ) {
    value = value.split( '=' );
    query_obj[value[0]] = value[1];
});

// query_obj = {"loc":"b","str":"test"}
Danijel
  • 12,408
  • 5
  • 38
  • 54
0

Given the little bit of info you have given I would do it like this:

var result = inputString.Split("=")[1];
Hogan
  • 69,564
  • 10
  • 76
  • 117
  • From my edit how would i get two parameter values from the url and save them in two separate variables? – Rob Morris Jan 03 '14 at 16:44
  • something like `var result = inputString.Split("?")[1].Select(z => { var x = z.Split("="); return new { p = x[0], v = x[1] }).ToArray();` Of course this has no error checking, but you get the idea. – Hogan Jan 03 '14 at 17:01