2

How to build the function in AngularJS to chceck the last part of the url?

My examples:

#/menu1/123/edit

#/menu2/444/create/new

#/menu3/sumbenu1/333/create/new

#/menu4/submenu2/subsubmenu1/subsubsubmenu1/543/edit

The thing is:

123 444 333 543 are the ID's which are generated outside Angular

I need to check the last parts of my url: /edit or /create/new.

The length of the url will be different (number of / inside url).

I have a controller in Angular to get the url:

.controller('urlCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {

    $rootScope.location = $location;
    $scope.hashPath = "#" + $rootScope.location.path().toString();
}]);

I'm adding the # character to the url because later I'm comparing it with my JSON.

I tried this solution but it didn't work (I also checked another solutions from this topic and nothing happened).

Any ideas?

EDIT:

Or how to check just the edit or create inside the url?

My solution is:

var path = $location.path();
var multisearch = path.search(/create|edit|new/);
console.log("multisearch: " + multisearch);

2 Answers 2

9

This should give you the desired result:

window.alert(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));

You could get the current URL by using: window.location.href Then you only need to get the part after the last '/'

Sign up to request clarification or add additional context in comments.

Comments

1

More efficient way:

location.pathname.split('/').slice(-1)[0]

In case of http://example.com/firstdir/seconddir/thirddir?queryparams#hash; it will give you thirddir

  • pathname will keep only the part of url after domain name and before query params
  • split will explode the url into array separated by /
  • slice will give you array containing only the last item
  • [0] will you last item as a string (in contrast to item of an array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.