'Get content between second last and last slash

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?



Solution 1:[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])

Solution 2:[2]

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).

Solution 3:[3]

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

s = 'http://localhost:8000/test/';
var content = s.match(/\/([^/]+)\/[^/]*$/)[1];

Solution 4:[4]

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.

Solution 5:[5]

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

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

It will return all data after second last /.

Solution 6:[6]

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`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dippas
Solution 2
Solution 3 Zen
Solution 4 Faizan Akram Dar
Solution 5 Tyler2P
Solution 6