Nerf
Nerf

Reputation: 938

javascript get id from url two options.

I have link:

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

Then I can get ID from this method:

    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;
            }

But if the link is:

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

The hash if from AngularJS routing.

Then how I can obtain the ID without the "#" character?

Upvotes: 0

Views: 66

Answers (2)

Aitor Gc
Aitor Gc

Reputation: 21

If you are using ui-router, your code should looks like something like that:

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

Then, since controller, you can get access to that id value, using $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"
  }
})();

Upvotes: 2

Elod Szopos
Elod Szopos

Reputation: 3526

You should remove the hash from the url, using the replace function.

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

This will remove the hash from the string for you.

Upvotes: 1

Related Questions