5

I need to extract the path before the # in my AngularJS app, so for example if my app url is:

http://www.domain.com/folder/app/#/home

I need to get only this portion:

http://www.domain.com/folder/app/

I've tried using $location.path, $location.abspath but couldn't find any function that can get me the first portion before the #. Can someone please help me by telling me what I am missing here? and if there is a way to get the first portion of the url (before the #)? Thanks

MChan
  • 6,842
  • 27
  • 83
  • 132

1 Answers1

7

You could split the path into the pathname and hash parts, and then use the pathname only:

$location.absUrl().split('#')[0]
// "http://www.example.com/folder/app/"

split is just a Javascript string operation returning an array:

'http://www.example.com/folder/app/#/home'.split('#')
["http://www.example.com/folder/app/", "/home"]
Zooly
  • 4,736
  • 4
  • 34
  • 54
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
  • Thanks a lot but using $location.path().split('#')[0] it returns the second portion of the url, that after the #, in other words /home am I missing something here? Thanks – MChan Jun 16 '14 at 21:55
  • Worked with $location.abspath().split('#')[0] thanks – MChan Jun 16 '14 at 22:01
  • @MChan - `$location.path().split('#')[0]` does not work because it only returns the portion of the url *after* the hash. So split is just returning a single-element array containing the original string -- i.e. the path (because the hash character was not found). – drwatsoncode Aug 11 '15 at 00:40
  • 7
    Looks like there's a typo, It should be `$location.absUrl().split('#')[0]` instead. – Tommy Oct 01 '15 at 22:25