Skip to content

Instantly share code, notes, and snippets.

@georgefs
Last active December 29, 2015 03:58
Show Gist options
  • Save georgefs/7611102 to your computer and use it in GitHub Desktop.
Save georgefs/7611102 to your computer and use it in GitHub Desktop.
簡單的js url encode & decode
function serialize(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
function parse_qs(qs){
qs.replace(/^.*\?|#.*$/g, '');
var result = {};
var data;
data = qs.split(/\?|&/);
for(index in data)
{
info = data[index].match(/^([^=]+)=([^=]+)$/);
if(!info){
continue;
}
result[info[1]] = info[1];
}
return result
}
function urljoin(target){
//保留path
clean_url = window.location.toString().replace(/(^\s+|\s+$)/g, '') //除空白
.replace(/[#?].*$/, '') //清茅點&參數
.replace(/\/[^/]*\.[^/]*$/, '') + "/"; //清檔案
domain = clean_url.match(/^https?:\/\/[^/]*/)[0]
protocol = domain.replace(/^(https?:)\/\/.*/, "$1");
// "http" 開頭 直接取代
if(target.match(/^https:\/\//)){
return target;
};
// "//" 開頭 保留protocol
if(target.match(/^\/\//)){
return protocol + target;
};
// "/" 開頭 保留domain
if(target.match(/^\//)){
return domain + target;
};
// "." 開頭 保留path
if(target.match(/^./)){
return clean_url + target;
};
}
urlstr = serialize({test: 12, foo: "bar"});
alert(urlstr);
result = parse_qs(urlstr)
alert(JSON.stringify(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment