Skip to content

Instantly share code, notes, and snippets.

@iahu
Created Sep 26, 2014
Embed
What would you like to do?
a js URI tool
function UriBuilder(uri) {
this.uri = uri;
this.parse();
return this;
}
UriBuilder.prototype.parse = function() {
// var match = this.uri.match(/(\w+:\/\/?.+?\..+\..+)?(\?.+)/);
var match = this.uri.split('?');
var params, o = {},t;
this.host = match[0];
params = match[1].split('&') || '';
params.forEach(function(p) {
t = p.split('=');
o[ t[0] ] = t[1];
});
this.params = o;
};
UriBuilder.prototype.build = function() {
var p = '';
var _params = this.params;
var key;
for (key in _params) {
if (_params.hasOwnProperty(key)) {
p += key + '=' + encodeURIComponent(_params[key]) + '&';
}
}
p = ('?'+p).slice(0,-1);
return this.host + p;
};
var b = new UriBuilder('http://www.codewars.com?page=1');
b.params.lang = 'zh-cn';
delete b.params.page;
console.info( b.build() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment