Javascript从url获取id有两个选项

javascript get id from url two options.

本文关键字:两个 选项 url 获取 id Javascript      更新时间:2023-09-26

我有链接:

      https://localhost:44301/.../.../2e8f0070-ff56-4f88-a316-b6d45f67b749/

然后我可以从这个方法得到ID:

    var index = window.location.href.lastIndexOf("/");
            if (index > 0 && index + 1 < window.location.href.length) {
                return window.location.href.substring(index + 1);
            } else {
                return null;
            }

但是如果链接是:

    https://localhost:44301/.../.../2e8f0070-ff56-4f88-a316-b6d45f67b749#/

来自AngularJS路由的哈希值。

那么我如何获得没有"#"字符的ID ?

如果你正在使用ui-router,你的代码应该看起来像这样:

.state('stateName', {
  url: '/object/:id',
  controller: 'ObjectCtrl',
  templateUrl: 'views/object.html'
  ...
});

然后,由于控制器,您可以访问id值,使用$stateParams

(() => {
  app.controller('ObjectCtrl', objectCtrl);
  objectCtrl.$inject = ['$scope', '$stateParams'];
  function objectCtrl($scope, $stateParams) {
    let id = $stateParams.id;
    console.log(id); // prints "2e8f0070-ff56-4f88-a316-b6d45f67b749"
  }
})();

您应该使用replace函数从url中删除哈希。

return window.location.href.substring(index + 1).replace('#', '');

这将为您从字符串中删除散列。