I have a url like the following
What is the tidiest way of getting test
from this using plain javascript/jQuery?
I have a url like the following
What is the tidiest way of getting test
from this using plain javascript/jQuery?
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).
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])
Don't you guys like regex? I think it is simpler.
s = 'http://localhost:8000/test/';
var content = s.match(/\/([^/]+)\/[^/]*$/)[1];
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.
let arr = link.split('/');
let fileName = arr[arr.length - 2] + "/" + arr[arr.length - 1];
It will return all data after second last /
.
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`