使用JavaScript将URL params(内联和后?)转换为对象

时间:2015-12-01 20:51:00

标签: javascript angularjs regex

我正在考虑创建一个vanilla JavaScript函数,该函数在给定特定URL路径的情况下从URL路径定义创建参数对象。与AngularJS作为routeParams服务的一部分的方式非常相似。例如......

给出以下路径定义:

/page1/{id}

实际的网址路径:

/page1/23?fname=Jon&lname=Doe

我想创建以下对象:

{
   "id": 23,
   "fname": "Jon",
   "lname": "Doe"
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:-1)

这就是我要找的东西。这是一个非常粗略的例子,但显然可以优化和清理代码。

function getParams(route, path) {
  var result = {};
  var queryString = (path.indexOf("?") > -1) ? path.substr(path.indexOf("?") + 1, path.length) : null;
  queryString.split("&").forEach(function(part) {
    if(!part) return;
    part = part.replace("+"," ");
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]");
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  var re = /{(\w+)}/g;
  var results = [];
  while (match = re.exec(route)) {
      results.push(match[1]);
  }
  var re2 = /\/page1\/id\/(\w+)\/name\/(\w+)/g;
  var results2 = re2.exec(path);
  for (var i = 0; i < results.length; i++) {
    result[results[i]] = results2[i + 1];
  }
  return result;
}
var route = "/page1/id/{id}/name/{name}";
var path = "/page1/id/23/name/leon?fname=Jon&lname=Doe";
var params = getParams(route, path);
console.log("PARAMS:", params);

以上代码输出:

PARAMS: Object {fname: "Jon", lname: "Doe", id: "23", name: "leon"}