1

How can I parse the below URL query string to get the value of the quantity parameter?

myurl/Channels/BuyCredits?quantity=2

I have tried numerous examples without success:

I just tried this example:

  marvmentApp.controller("channelCreditController", function($scope, $http, $compile, $location) {
    var params, test2;
    $scope.parseQueryString = function() {
      var objURL, str;
      str = window.location.search;
      objURL = {};
      str.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) {});
      objURL[$1] = $3;
      return;
      return objURL;
    };
    params = $scope.parseQueryString();
    test2 = params['quantity'];
    debugger;
  });

I keep getting an error $1 is udefined

1
  • $0 - $3 only exist within the scope of your empty function function($0, $1, $2, $3) {}. (And there are much easier ways to extract a query param.) Commented Nov 1, 2014 at 19:02

1 Answer 1

1

Use the JavaScript location.search property. It will return the query string of your URL (including the "?" symbol).

If the URL is http://www.example.org/index.php?param=arg

The value location.search is ?param=arg.

To remove the "?", use the JS replace method:

var url = "?param=arg"; // pretend that the variable "url" is the query string
url = url.replace(/[\?]/,"");
document.getElementById('output').innerHTML = "Query string is: \"" + url + "\"";
<p id="output"></p>

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.