How to extract base URL from a string in JavaScript?

Viewed 303111

I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).

For example, given something like:

http://www.sitename.com/article/2009/09/14/this-is-an-article/

I'd like to get:

http://www.sitename.com/

Is a regular expression the best bet? If so, what statement could I use to assign the base URL extracted from a given string to a new variable?

I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.

21 Answers

Well, URL API object avoids splitting and constructing the url's manually.

 let url = new URL('https://stackoverflow.com/questions/1420881');
 alert(url.origin);

A good way is to use JavaScript native api URL object. This provides many usefull url parts.

For example:

const url = 'https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript'

const urlObject = new URL(url);

console.log(urlObject);


// RESULT: 
//________________________________
hash: "",
host: "stackoverflow.com",
hostname: "stackoverflow.com",
href: "https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript",
origin: "https://stackoverflow.com",
password: "",
pathname: "/questions/1420881/how-to-extract-base-url-from-a-string-in-javaript",
port: "",
protocol: "https:",
search: "",
searchParams: [object URLSearchParams]
... + some other methods

As you can see here you can just access whatever you need.

For example: console.log(urlObject.host); // "stackoverflow.com"

doc for URL

To get the origin of any url, including paths within a website (/my/path) or schemaless (//example.com/my/path), or full (http://example.com/my/path) I put together a quick function.

In the snippet below, all three calls should log https://stacksnippets.net.

function getOrigin(url)
{
  if(/^\/\//.test(url))
  { // no scheme, use current scheme, extract domain
    url = window.location.protocol + url;
  }
  else if(/^\//.test(url))
  { // just path, use whole origin
    url = window.location.origin + url;
  }
  return url.match(/^([^/]+\/\/[^/]+)/)[0];
}

console.log(getOrigin('https://stacksnippets.net/my/path'));
console.log(getOrigin('//stacksnippets.net/my/path'));
console.log(getOrigin('/my/path'));

Implementation:

const getOriginByUrl = url => url.split('/').slice(0, 3).join('/');

Test:

getOriginByUrl('http://www.sitename.com:3030/article/2009/09/14/this-is-an-article?lala=kuku');

Result:

'http://www.sitename.com:3030'
Related