Decomposing, manipulating, and recomposing URLs in Javascript
I recently had a need to decompose a URL, do some stuff with the parameters, and reassemble it. I later had a need to take another URL and create a form on the fly, because using GET could overrun the URL character limit imposed by Internet Explorer.
Here’s my code for a decomposition and composition pair, plus the code to create a form dynamically using the output of the url_decompose() function.
/**
* @param String url the URL to be decomposed
* @return Object with full path in .path, params in arrays in .params
**/
function url_decompose(url){
if(url.indexOf('?') == -1){ return {path: url, params: {} }; }
path = url.substring(0, url.indexOf('?'));//get the path before the ?
qs = url.substring(url.indexOf('?')+1);
qsa = qs.split('&');
params = new Object();
for (var kv in qsa) {
var kva = qsa[kv].split('=');
var k = kva[0];
var v = kva.slice(1, kva.length).join("=");
params[k] = params[k] || new Array();
params[k].push(v);
}
return {path: path, params: params};
}
/**
* @param Object output of url_decompose()
* @return String reassembled URL
**/
function url_compose(urlObject){
if(!urlObject.path){return urlObject;}
var urlString = '';
var params = [];
for (var kv in urlObject.params){
if(kv.length > 0){
params.push(
encodeURIComponent(kv) +
'=' +
encodeURIComponent(urlObject.params[kv][0]));
}
}
urlString = urlObject.path +
(params.length > 0 ? '?' + params.join('&') : '');
return urlString;
}
/**
* @param String path the path to be accessed
* @param Array params associative array or object w/ params in key/value pairs
* @param String method null for post or whatever method the form should use
**/
function do_post(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
for(var idx in params[key]){
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key][idx]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
If I’ve omitted an edge case, please do let me know and I’ll amend my code. I really do need to get one of those code highlighter plugins installed now that I’m doing more code examples.





