0

Currently with my code:

window.location.pathname.split('/')[3]

I can get "comparative" from:

http://localhost/study/78/comparative

But it's possible that some subdirectories will be added to the URI.

How can I get the last substring (the most to the right) on the URI separated with / ?

pmiranda
  • 7,602
  • 14
  • 72
  • 155

2 Answers2

2

Try with slice

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

console.log("http://localhost/study/78/comparative".split('/').slice(-1)[0])
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
0

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

or

window.location.pathname.split('/').pop()

or

window.location.pathname.substr(window.location.pathname.lastIndexOf("/") + 1)

Robin
  • 4,902
  • 2
  • 27
  • 43
  • 3
    what's the point of `.slice(-1)` if you're going to call `.pop()`? – Thomas Jun 28 '19 at 14:20
  • The slice() method returns the selected elements in an array, as a new array object. And The pop() method removes the last element of an array, and returns that element. `.slice(-1)` returns you an array with last sub-string, and `.pop()` pull out the value of sub-string. @Thomas – Robin Jun 28 '19 at 14:23
  • why not just get the last value from the array that `.split('/')` returns? why do you need to `.slice(-1)` here? like `window.location.pathname.split('/').pop()` – Thomas Jun 28 '19 at 14:26
  • 1
    @Robin what Thomas is saying is that you already have an array on which you can "pull out the value of sub-string" using `.pop()` before you even call `.slice(-1)` – Patrick Roberts Jun 28 '19 at 14:26
  • I understand now , you don't need slice when use `split`, split itself return the array of substring. @PatrickRoberts – Robin Jun 28 '19 at 14:30
  • `window.location.pathname.split('/').pop()` is the winner. – pmiranda Jun 28 '19 at 14:33
  • @Thomas answer is edited, with `pop()` you don't need use `slice()` – Robin Jun 28 '19 at 14:33