Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first part of a url path

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

like image 927
Cameron Avatar asked Nov 10 '11 15:11

Cameron


People also ask

How to get specific part of URL in JavaScript?

The easiest way is to use a regex or split : url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method"; lastPart = url.

How to get current URL path in JavaScript?

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.

How do I get pathname?

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.


2 Answers

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

like image 127
Samuel Liew Avatar answered Sep 20 '22 01:09

Samuel Liew


var first = $(location).attr('pathname');  first.indexOf(1);  first.toLowerCase();  first = first.split("/")[1];  alert(first); 
like image 20
Dogbert Avatar answered Sep 21 '22 01:09

Dogbert