3

Suppose I have a URL like this:

http://www.example.com/apples?myParam=123&myOtherParam=456

How do I use Knockout JS to retrieve the values of myParam and myOtherParam ?

Jesse Lynn
  • 325
  • 5
  • 15
  • is this url from the brower's address bar, inside of a textbox, or stored in a variable? In any case, as long as you can get to it, you can use the string.split function to parse the data. – NPToita Nov 27 '15 at 04:32
  • it's a URL from address bar – Jesse Lynn Nov 27 '15 at 05:45
  • 1
    See also: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Roy J Nov 27 '15 at 14:05

2 Answers2

3

To parse the location. [window.location gives you the current document's location]

var paramsString = window.location.split("?")[1];
var paramValues = paramsString.split("&");
var params = new Array();
for(var param in paramValues){
    var paramValue = param.split("=");
    params[paramValue[0]] = paramValue[1];
}

to use the params:

var myParam = params.myParam; //or
var myOtherParam = params['myOtherParam'];
NPToita
  • 238
  • 2
  • 9
1

You can also take a look to this post which shows a nice, simple and small fuction:

function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace( 
    /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    function( m, key, value ) { // callback
        vars[key] = value !== undefined ? value : '';
    }
);

if ( param ) {
    return vars[param] ? vars[param] : null;    
}
return vars;}

then you can get the variable in a similar way to PHP:

name = $_GET('name')

Here is the full article: read URL params with Javascript

Alberto S.
  • 1,805
  • 23
  • 39