Skip to content

Instantly share code, notes, and snippets.

@ifyour
Last active June 12, 2017 06:42
Show Gist options
  • Save ifyour/6b0abafc6319fe3b00b173a0ac96a125 to your computer and use it in GitHub Desktop.
Save ifyour/6b0abafc6319fe3b00b173a0ac96a125 to your computer and use it in GitHub Desktop.
利用正则表达式实现将查询字符串转成 Javscript 对象
const URL = "http://helloworld.com?user=Jack&pwd=123456&hobby=read";
const RE = /(\?|\&)([^=]+)\=([^&]+)/g;
let paramsObject = {};
URL.replace(RE, (match, p1, p2, p3) => {
paramsObject[p2] = p3;
});
console.log(paramsObject);
// will be { user: 'Jack', pwd: '123456', hobby: 'read' }
//*************************************************************
// ES5 方法封装 getUrlArgs 返回格式 {has:[true|false], data:{}}
//*************************************************************
getUrlArgs = function() {
var URL = window.location.href;
var RE = /(\?|\&)([^=]+)\=([^&]+)/g;
var result = {
has: false,
data: {}
};
URL.replace(RE, function(match, p1, p2, p3) {
result.data[p2] = p3;
});
for (var prop in result.data) {
result.has = true;
break;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment