Remove subdirectories from a URL string

javascript

I use GitHub to manage code that I’ll want to re-use. I had trouble finding a canned function to remove the subdirectory path from a URL string – so I wrote one and added it to my latest public repository: https://github.com/pacea87/ap-utils

I’ll keep adding useful code to it – and feel free to make a pull request and contribute yourself. This code should focus on utility functions for manipulating data in interesting ways. Below is the JavaScript code for removing the subdirectories from a URL string. This will also strip away any query string parameters.

function removeSubdirectoryFromUrlString(url){
  
  var ssl = false;
  if(url.indexOf("https://")){
    ssl = true;
  }

  url = url.replace("http://", "");
  url = url.replace("https://", "");
  var pathArray = url.split("/")
  url = pathArray[0];
  if(ssl){
    url = "https://" + url;
  }else{
    url = "http://" + url;
  }

  return url;
}

Now, you can get the current page’s URL, and strip off everything after the host name:

var url = window.location.href;
var baseUrl = removeSubdirectoryFromUrlString(url);
console.log(baseUrl);

Another example:

var url = "https://www.antpace.com/blog/index.php/2018/12/";
var baseUrl = removeSubdirectoryFromUrlString(url);

//This will return "https://www.antpace.com"
console.log(baseUrl); 

I used this code to re-write all URL references in an iFrame to be absolute. My implementation loops through all image, anchor, and script tags on the source site. It determines if each uses an absolute reference, and if not re-writes it as one. This was part of a project that uses a visual editor to allow users to manipulate a remote site. Check out my source code below.

pageIframe.contents().find("img").each(function(){
  var src = $(this).attr("src");
  if(src && src.length > 0 && src.indexOf("//") == -1){  //if not absolute reference
    var url = iframeUrlString;
    if(src.charAt(0) == "/"){ //only do this if the src does not start with a slash
      url = removeSubdirectoryFromUrlString(url); 
    }
    src = url+"/"+src
  }
  $(this).attr("src", src);
});

pageIframe.contents().find("script").each(function(){
  var src = $(this).attr("src");
  if(src && src.length > 0 && src.indexOf("//") == -1){
    var url = iframeUrlString;
    if(src.charAt(0) == "/"){
      url = removeSubdirectoryFromUrlString(url); 
    }
    src = url+"/"+src
  }
  $(this).attr("src", src);
});

pageIframe.contents().find("link").each(function(){
  var src = $(this).attr("href");
  if(src && src.length > 0 && src.indexOf("//") == -1){
    var url = iframeUrlString;
    if(src.charAt(0) == "/"){
      url = removeSubdirectoryFromUrlString(url); 
    }
    src = url+"/"+src
  }
  $(this).attr("href", src);
});

If you liked this, check out my other post about my reusable code framework for web apps, A framework for web apps and startups.