You are here

14 August 2013

This function alters url get parameters using javascript. The function takes to consideration all aspects of url (parameter existis, hash, parameter doesn't exist). For an example if you need to be able to change url parameter "tag" value to something, lets say "tutorials". If the "tag" doesn't exist, it adds at the end of the url without breaking or making double entries.

Source code viewer
  1. /**
  2.  * Add a parameter to an url.
  3.  *
  4.  * @param url
  5.  * Initial url, can be with or without existing parameters.
  6.  * @param param
  7.  * Parameter that gets
  8.  * @param value
  9.  * @returns {*}
  10.  */
  11. function url_parameter(url, param, value) {
  12. 'use strict';
  13.  
  14. // Find given parameter.
  15. var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
  16. parts = url.toString().split('#'),
  17. hash = parts[1],
  18. qstring = /\?.+$/,
  19. return_url = parts[0];
  20. url = parts[0];
  21.  
  22.  
  23. // Check for parameter existance: Replace it and determine whether & or ? will be added at the beginning.
  24. if (val.test(url)) {
  25. // If value empty and parameter exists, remove the parameter.
  26. if (!value.length) {
  27. return_url = url.replace(val, '');
  28. }
  29. else {
  30. return_url = url.replace(val, '$1' + param + '=' + value);
  31. }
  32. }
  33. // If there are query strings add the param to the end of it.
  34. else if (qstring.test(url)) {
  35. return_url = url + '&' + param + '=' + value;
  36. }
  37. // Add if there are no query strings.
  38. else {
  39. return_url = url + '?' + param + '=' + value;
  40. }
  41.  
  42. // Add hash if it exists.
  43. if (hash) {
  44. return_url += '#' + hash;
  45. }
  46.  
  47. return return_url;
  48. }
Programming Language: Javascript