Get current URL domain and page name with JavaScript
Using the cross-browser supported document.URL (returns the current page's entire address, as seen in the address bar), we'll get the current URL and be able to extract its part with a script. alert( document.URL ); // all-including: from protocol to dynamic arguments
Ajax arguments in dynamic URLs are unpredictably formatted: let's first remove and store them, by using indexOf() to test for their presence, and substring() to separate them from the main URL: var url = document.URL, clientArgs = "", serverArgs = "";
if( url.indexOf("#")>0 ) { // check for anchor links or Ajax dynamic URL's clientArgs = url.substring( url.indexOf("#")+1 ); // everything after # url = url.substring( 0, url.indexOf("#") ); // anything before # }
Let's now do the same for server-side arguments (PHP, ASP.NET, JSP, etc.) if( url.indexOf("?")>0 ) { // check for question mark (server side args) serverArgs = url.substring( url.indexOf("?")+1 ); // everything after # url = url.substring( 0, url.indexOf("?") ); // anything before # }
To avoid blank elements, lets first remove all multiple slashes in a row with replace(): url = url.replace( /\/+/g, "/" );
We'll use split() to "explode" the URL into pieces at each forward slash character (/). url = url.split( "/" ); // url string variable now an arrayAnd here's the universal breakdown for URL pieces: • url[0] = protocol (http / https). • url[1] = domain name, including any subdomain (e.g., sstut.com / www.sstut.com / js.sstut.com ). • url[ url.length-1 ] = current page (e.g., index.html). Note: any array element between (but not including) 1 (domain) and Array.length-1 (page) are folders and subdirectories; the array for a top-level (root) page URL is 3.