If I have a url like:
http://localhost:53830/Organisations/1216/View
I want to alert the first part of the url path in lowercase format e.g. 'organisations'
So far I have:
var first = $(location).attr('pathname'); first.indexOf(1); first.replace('/', ''); first.toLowerCase(); alert(first);
but it's not working as intended. Can anyone help? Thanks
The easiest way is to use a regex or split : url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method"; lastPart = url.
Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.
To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string. Then we can use the pathname property to get the URL path. For instance, we write: const url = 'http://www.example.com/foo/path2/path3/path4'; const { pathname } = new URL(url); console.
This will never throw an error because pathname always starts with a /
, so the minimum length of the resulting array will be 2 after splitting:
const firstPath = window.location.pathname.split('/')[1];
If we are at the domain root, the returned value will be an empty string ""
.
var first = $(location).attr('pathname'); first.indexOf(1); first.toLowerCase(); first = first.split("/")[1]; alert(first);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With