JavaScript Gets the current url root directory of path

  • 2021-06-29 09:37:46
  • OfStack

Mainly used for Location objects, containing information about the current URL, is a part of the Window object that can be accessed through the window.location property.

Method 1. js's method of getting the project root path


function getRootPath(){
  var curPageUrl = window.document.location.href;
  var rootPath = curPageUrl.split("//")[0] + curPageUrl.split("//")[1].split("/")[0] 
          + curPageUrl.split("//")[1].split("/")[1];
  return rootPath;
}

Method 2 (window.document.location.href/window.document.location.pathname) --------------------- Turn from network


function getRootPath_web() {
 // Get the current web address, such as:  http://localhost:8083/uimcardprj/share/meun.jsp
 var curWwwPath = window.document.location.href;
 // The directory after getting the host address, such as:  uimcardprj/share/meun.jsp
 var pathName = window.document.location.pathname;
 var pos = curWwwPath.indexOf(pathName);
 // Get the host address, such as:  http://localhost:8083
 var localhostPaht = curWwwPath.substring(0, pos);
 // Get Strip "/" Project name, such as: /uimcardprj
 var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
 return (localhostPaht + projectName);
}

Method 3 (window.location.pathname/window.location.protocol/window.location.host)


function getRootPath_dc() {
 var pathName = window.location.pathname.substring(1);
 var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
 if (webName == "") {
  return window.location.protocol + '//' + window.location.host;
 }
 else {
  return window.location.protocol + '//' + window.location.host + '/' + webName;
 }
}

Note:

1. document implies a document object, window implies a window object, and there can be multiple document objects under a window.
So there is only one window.location.href under one window, but there may be more than one document.URL, document.location.href------------------------------------------------------------------- Turn from the network

2. window.location.href and document.location.href can be assigned values and jump to other pages. document

3. Location object details refer to w3school https://www.ofstack.com/w3school/jsref/dom_obj_location.htm

This site This site adds:

Exclude advertising implementations for certain catalogs


var pathName = window.document.location.pathname;
var projectName = pathName.substring(1, pathName.substr(1).indexOf('/') + 1);
var ad_projectlist = ',,web,html5,css,';
if(ad_projectlist.indexOf(','+projectName+',') < 0){
 alert("web,html5,css Several directory codes do not execute ");
}

Related articles: