Created
November 26, 2014 18:11
-
-
Save filippomangione/e3543eff642220cd6ca1 to your computer and use it in GitHub Desktop.
querystring.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('./underscore.js'); | |
/* | |
* Append querystring to the url | |
* @param string url | |
* @param object parameters | |
*/ | |
function qs(url, params){ | |
if(params){ | |
var reg; | |
for(var x in params){ | |
if(url.indexOf(x)>-1){ | |
var str = "[\\?\\&]"+x+"=[^\\&]*"; | |
reg = new RegExp(str); | |
url = url.replace(reg,''); | |
} | |
} | |
} | |
return url + (!_.isEmpty(params) ? ( url.indexOf('?') > -1 ? "&" : "?" ) + param(params) : ''); | |
} | |
/* | |
* Param | |
* Explode/Encode the parameters of an URL object | |
* @param object | |
*/ | |
function param(o){ | |
var a = []; | |
for( var x in o ){ | |
if( o.hasOwnProperty(x) ){ | |
a.push( [x, o[x] === '?' ? '?' : encodeURIComponent(o[x]) ].join('=') ); | |
} | |
} | |
return a.join('&'); | |
} | |
console.log(qs('http://domain.com',{foo:'bar',baz:'?'})); // http://domain.com?foo=bar&baz=foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment