1

I have a url like the following

http://localhost:8000/test/

What is the tidiest way of getting test from this using plain javascript/jQuery?

  • 1
    Possible duplicate of [How to pull the file name from a url using javascript/jquery?](http://stackoverflow.com/questions/1302306/how-to-pull-the-file-name-from-a-url-using-javascript-jquery) – dippas Jun 18 '16 at 16:20
  • @dippas but I am trying to get the content between the second last and last slash –  Jun 18 '16 at 16:21
  • It is the same as the duplicated question. :) – dippas Jun 18 '16 at 16:29

6 Answers6

1

The section of the URL you are referring to is called the path, in Javascript this can be accessed by reading the contents of the location.pathname property.

You can then use a regular expression to access only the final directory name (between the last two slashes).

Rob Farr
  • 853
  • 1
  • 9
  • 17
1

You can do it easily like following using split() method.

var str = 'http://localhost:8000/test/';
var arr = str.split('/'); 

console.log(arr[arr.length-2])
dippas
  • 58,591
  • 15
  • 114
  • 126
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
  • Are you sure last slash is mandatory? Because `http://localhost:8000/test` is perfectly valid URL AFAIK. I think this would be more accurate to handle all possible cases: https://jsfiddle.net/jxu945y9/ – A. Wolff Jun 18 '16 at 16:30
  • OK. But OP asked for the content between second last and last slash. @A.Wolff – Ibrahim Khan Jun 18 '16 at 16:32
  • @Azim Ya and then you answer question as asked but not sure what exactly means OP by `I have a url like the following`. Is it a string? Current page location? Element href or src? Or what? – A. Wolff Jun 18 '16 at 16:33
  • Hm. OP is not saying anything. @A.Wolff – Ibrahim Khan Jun 18 '16 at 16:50
0

Don't you guys like regex? I think it is simpler.

s = 'http://localhost:8000/test/';
var content = s.match(/\/([^/]+)\/[^/]*$/)[1];
Zen
  • 5,065
  • 8
  • 29
  • 49
0

JS split() function does magic with location.pathname .

var str = location.pathname.split('/'); 

var requiredString = str[str.length -2];

requiredString will contain required string, you may console log it by console.log(requiredString) or use it anywhere else in the program.

0
let arr = link.split('/');

let fileName = arr[arr.length - 2] + "/" + arr[arr.length - 1];

It will return all data after second last /.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Apr 25 '22 at 08:42
0

You can use :

window.location.pathname

returns the path and filename of the current page.

with the split() function

To learn more about window.location in w3 School :

https://www.w3schools.com/js/js_window_location.asp

//window.location.pathname return /test

 var path=window.location.pathname.split("/");

 var page=path[0]; //return test`
Omar Hussien
  • 313
  • 1
  • 9