Languages
[Edit]
EN

JavaScript - how to get, set, and manage url hash parameters ?

13 points
Created by:
Kate_C
21490

In JavaScript it is possible to get and set url hash parameters using following logic.

1. Url hash parameters logic example

index.htm file:

<!doctype html>
<html lang="en">
<head>
  <script src="hash-parameters.js"></script>
</head>
<body>
  <script>

	HashParameters.addListener(function() {
		var text = '---------- Hash changed...<br />';
		
		HashParameters.iterateParameters(function(name, value) {
			text += name + ': ' + value + '<br />';
		});
		
		text += '-----------------------------<br />';
		
		document.body.innerHTML += text;
	});
	
	HashParameters.setParameter('page-number', '5');
	HashParameters.setParameter('page-size', '50');
	
	var pageNumber = HashParameters.getParameter('page-number', '1');
	var pageSize = HashParameters.getParameter('page-size', '20');
	var pageOrdering = HashParameters.getParameter('page-ordering', 'A-Z');
	
	document.body.innerHTML += 'page-number: ' + pageNumber + ', ' 
		+ 'page-size: ' + pageSize + ', ' 
		+ 'page-ordering: ' + pageOrdering
		+ '<br />';
		
	//HashParameters.removeParameter('page-size');
	//HashParameters.clearParameters();

  </script>
</body>
</html>

hash-parameters.js file:

// 'use strict';

(function (window) {
    var PARAMETER_REGEX = /^([^=]+)(?:=(.*))?$/g;

    function matchParameter(text) {
        PARAMETER_REGEX.lastIndex = 0;
        return PARAMETER_REGEX.exec(text);
    }

    function decodeComponent(part) {
        if (part) {
            return decodeURIComponent(part);
        }
        return null;
    }

    function parseParameters(request) {
        var parameters = {};
        var postfix = request.substring(1);
        if (postfix) {
            var parts = postfix.split('&');
            for (var i = 0; i < parts.length; ++i) {
                var part = parts[i];
                if (part) {
                    var match = matchParameter(part);
                    if (match) {
                        var name = decodeComponent(match[1]);
                        parameters[name] = decodeComponent(match[2]);
                    }
                }
            }
        }
        return parameters;
    }

    window.HashParameters = new function () {
        var cache = null; // current hash for changes detection

        var parameters = {}; // parsed and decoded parameters
        var listeners = []; // hash initialized or typed event methods

        function removeItem(array, item) {
            var index = array.indexOf(item);
            if (index == -1) {
                return;
            }
            array.splice(index, 1);
        }

        function renderHash(parameters) {
            var postfix = '';
            for (var el in parameters) {
                var parameter = parameters[el];
                if (postfix) {
                    postfix += '&';
                }
                postfix += encodeURIComponent(el);
                if (parameter) {
                    postfix += '=' + encodeURIComponent(parameter);
                }
            }

            return '#' + postfix;
        }

        function updateParameters() {
            var hash = window.location.hash;
            if (hash == cache) {
                return false;
            }
            parameters = parseParameters(cache = hash);
            return true;
        }

        function updateHash() {
            var hash = renderHash(parameters);
            if (hash == cache) {
                return false;
            }
            window.location.hash = cache = hash;
            return true;
        }

        function fireListeners() {
            for (var i = 0; i < listeners.length; ++i) {
                var listener = listeners[i];
                listener();
            }
        }

        window.addEventListener('hashchange', function () {
            if (updateParameters()) {
                fireListeners();
            }
        });

        updateParameters();

        // public methods

        this.addListener = function addListener(action) {
            if (action instanceof Function) {
                listeners.push(action);
                var result = function () {
                    if (action) {
                        removeItem(listeners, action);
                        action = null;
                    }
                };
                return result;
            }

            throw new Error('Indicated listener action is not function type.');
        };

        this.removeListener = function removeListener(action) {
            removeItem(listeners, action);
        };

        this.getParameter = function getParameter(name, defaultValue) {
            return parameters[name] || defaultValue;
        };

        this.setParameter = function setParameter(name, value) {
            parameters[name] = value;
            updateHash();
        };

        this.removeParameter = function setParameter(name) {
            delete parameters[name];
            updateHash();
        };

        this.clearParameters = function clearParameters() {
            parameters = {};
            updateHash();
        };

        this.iterateParameters = function iterateParameters(action) {
            for (var el in parameters) {
                var value = parameters[el];
                action(el, value);
            }
        };
    };
})(window);

Result:

Hash parameters logic with changed url after page loaded.
Hash parameters logic with changed url after page loaded.

See also

  1. JavaScript - how to get url request parameters in JavaScript? 
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join