Posted By

cerxx on 03/24/19


Tagged

js-hacks


Versions (?)

How to get URL-query string values ??in javascript?


 / Published in: JavaScript
 

URL: http://qaru.site/questions/219/how-can-i-get-query-string-values-in-javascript

jQuery plugin method

  1. (function($) {
  2. $.QueryString = (function(paramsArray) {
  3. let params = {};
  4.  
  5. for (let i = 0; i < paramsArray.length; ++i)
  6. {
  7. let param = paramsArray[i]
  8. .split('=', 2);
  9.  
  10. if (param.length !== 2)
  11. continue;
  12.  
  13. params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
  14. }
  15.  
  16. return params;
  17. })(window.location.search.substr(1).split('&'))
  18. })(jQuery);
  19.  
  20. Usefull:
  21. //Get a param
  22. $.QueryString.param
  23. //-or-
  24. $.QueryString["param"]
  25. //This outputs something like...
  26. //"val"
  27.  
  28. //Get all params as object
  29. $.QueryString
  30. //This outputs something like...
  31. //Object { param: "val", param2: "val" }
  32.  
  33. //Set a param (only in the $.QueryString object, doesn't affect the browser querystring)
  34. $.QueryString.param = "newvalue"
  35. //This doesn't output anything, it just updates the $.QueryString object
  36.  
  37. //Convert object into string suitable for url a querystring (Requires jQuery)
  38. $.param($.QueryString)
  39. //This outputs something like...
  40. //"param=newvalue&param2=val"
  41.  
  42. //Update the url/querystring in the browser location bar with the $.QueryString object
  43. history.replaceState({}, '', "?" + $.param($.QueryString));
  44. //-or-
  45. history.pushState({}, '', "?" + $.param($.QueryString));

Report this snippet  

You need to login to post a comment.