0

I'm expecting URLs in this for:

/user/username

but end users can also add whatever get parameters they want, like so:

/user/username?foo=bar

With that said, using AngularJS, what's the preferred way for me to get just the username (which appears after /user/) without anything else after it?

isherwood
  • 58,414
  • 16
  • 114
  • 157
SilentDev
  • 20,997
  • 28
  • 111
  • 214

3 Answers3

1

You should use the $location service and its .path() method, then use a regular split() and indexing.

Aaron
  • 24,009
  • 2
  • 33
  • 57
1

I doubt there's a dedicated function for it but it seems easy enough to pull it out of the string with the query. Get the path with $location.path() and then both of these does the job for you.

url.substring(6, (url.indexOf('?') != -1 ? url.indexOf('?') : url.length))

url.split('/')[2].split('?')[0]

Same question here: Is there a built-in way to get the current URL without any query parameters?

Community
  • 1
  • 1
  • `$location.path()` does not return the search parameters, there's no need dealing with the `?` – Aaron Nov 09 '15 at 09:39
0

you can use window.location or $location service to get the path and then using split function like this

var url = "/user/username?foo=bar";
var check = url.split('/user/');
var username = check[1].split('?');
console.log(username[0]);

you can find username by applying multiple split on your url. hope this is what you want.

sahil0021
  • 77
  • 1
  • 7
  • It's good that you want to help, but please avoid repetition of an already existing answer. – ViG Mar 26 '18 at 17:28