In web development, it’s often necessary to extract parameters from a URL, whether they’re in hash tags or search tags. This tutorial presents a custom function designed to fetch all parameters from either type of tag and store them in a config
object. This object can then be used for various further processes.
Table of Contents
ToggleThe getLinkParameters Function
The getLinkParameters
function is designed to fetch parameters from a URL. Here’s the function:
function getLinkParameters(){
var config = {};
if(location.search){
addToModel(location.search.slice(1).split('&'));
}
if(location.hash){
addToModel(location.hash.slice(1).split('&'));
}
function addToModel(searchParams){
for(var s in searchParams){
var q = searchParams[s].split('=');
config[q[0]] = !!q[1] ? unescape(q[1]) : "";
}
}
}
How Does getLinkParameters Work?
The getLinkParameters
function works as follows:
- It creates an object (
config
) to store the URL parameter values. - It checks whether the URL contains a “Hash” or “Search” tag.
- It passes the values from these tags to the
addToModel
function, after slicing and splitting them by “&”. - The
addToModel
function checks each parameter, splits it by “=”, and stores the value in theconfig
object.
By the end of this process, all parameters from the URL are stored in the config
object.
The updateHashlink Function
The updateHashlink
function is used to update the hash tag in the URL when specific site data changes (for example, when a tab on the site is changed). Here’s the function:
function updateHashlink(data){
var params = [];
params.push("data="+data);
params = params.join('&');
location.hash = params;
return params;
}
How Does updateHashlink Work?
The updateHashlink
function works as follows:
- It creates a temporary
params
array to store parameter values. - It adds data to
params
using thepush
function. - It updates the hash tag in the URL using
location.hash = params
.
By using these two functions, you can effectively manage URL parameters and dynamically update the URL based on changes in site data. This can be particularly useful in single-page applications where the state of the application is often reflected in the URL.