How to Get the Base URL in JavaScript?

If you want to know how to retrieve or get the base URL in JavaScript, this article is for you.

In this article, we will guide you and cover everything you need to know, with step-by-step instructions and code examples.

Don’t miss out on this essential knowledge for any web developer. Continue to read on to learn more about JavaScript get base url!

What is URL?

URL stands for Uniform Resource Locator.

A URL is like the address of a webpage or resource on the Internet. It consists of a protocol (like “https://”) followed by the address.

In addition to that, a URL is like a house address for the internet. Just as you need an address to find a house, you need a URL to find a specific web page or resource online.

The URL tells your web browser where to go to find the information you want.

It includes things like the protocol (HTTP or HTTPS), the domain name (www.itsourcecode.com), and sometimes additional details like the specific page or files you’re looking for.

Here’s the syntax to get URL in JavaScript:

document.URL

How to get base URL in JavaScript?

To start, open the website https://itsourcecode.com/ and then type the given code into the console of your web browser.

You can use Ctrl + Shift + J for Windows and Command+ Option + J for Mac to pen the Console panel.

const url_var = document.URL;

console.log(url_var);

Output:

get url base javascript

Another approach to retrieve the base URL from a given URL in JavaScript is by creating a URL object instance and extracting the necessary parts of the base URL from it.

const url = new URL("https://itsourcecode.com/javascript-online-compiler-editor/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)

Output:

https://itsourcecode.com

How to get base from the current URL in JavaScript?

To get the base URL of the current webpage using JavaScript, you can make use of the window.location object.

Here’s the syntax:

window.location.href

Here’s the example code:

const url_var = window.location.href;
console.log(url_var);

Here’s an example: Go to the website https://itsourcecode.com/topics/blogs/ and then type the given code into your web browser’s console.

You can use Ctrl + Shift + J for Windows and Command+ Option + J for Mac to pen the Console panel.

Output:

https://itsourcecode.com/topics/blogs/

The document.URL, which we discussed above, is also used to get the current URL.

Just like window.location, however, we used window.location to show you more functionalities.

Here’s another example in HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>Base URL Example</h1>
    <p id="output"></p>

    <script>
        // Get the base URL and host name


        const baseUrl = window.location.origin;
        const host = window.location.host;

        // Output the base URL and host name to the page

        document.getElementById("output").innerHTML = `Base URL: ${baseUrl}<br>Host: ${host}`;
    </script>
</body>
</html>

How to get URL origin in JavaScript?

The window.location.origin property provides the base URL along with the protocol (e.g., “https://www.sample.com”), while the window.location.host property gives you just the host name (e.g., “www.sample.com”).

Here’s the syntax:

window.location.origin

Here’s the example code:

const url_var = window.location.origin;
console.log(url_var);

Here’s an example: Go to the website https://itsourcecode.com/topics/blogs/ and then type the given code into your web browser’s console.

You can use Ctrl + Shift + J for Windows and Command+ Option + J for Mac to pen the Console panel.

Output:

https://itsourcecode.com

How to get the base URL from a string in JavaScript?

If you have a URL as a string and want to extract the base URL from it, you can do that by using the URL constructor and the URL.origin property.

Here’s an example to help you understand:

const urlString = "https://itsourcecode.com/topics/blogs/";
const url = new URL(urlString);
const baseUrl = url.origin;
console.log(baseUrl);

Output:

https://itsourcecode.com

If you want to get the location origin and host along with pathArray, execute the following.

Here’s an example: Go to the website https://itsourcecode.com/topics/blogs/ and then type the given code into your web browser’s console.

You can use Ctrl + Shift + J for Windows and Command+ Option + J for Mac to pen the Console panel.

var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );

console.log("Base URL:", base_url);
console.log("Host:", host);
console.log("Path Array:", pathArray);

Output:

Base URL: https://itsourcecode.com
Host: itsourcecode.com
Path Array: (4) ['', 'topics', 'blogs', '']

Conclusion

In conclusion, this article provided easy-to-understand instructions and examples on how to get the base URL in JavaScript.

We explained that a URL is like an address for a webpage or resource on the Internet and discussed its components, such as the protocol and domain name.

We covered three main methods for getting the base URL in JavaScript: using a document.URL, creating a URL object, and utilizing window.location and window.location.origin.

Each method was accompanied by a sample code and instructions on how to use it in the browser console.

We also provided an example of extracting the base URL from a string using the URL constructor.

By following the solutions given above, developers can easily obtain the base URL for their web applications.

We are hoping that this article provides you with enough information that helps you understand the JavaScript get base URL .

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Quick step-by-step summary (click to expand)
  1. What is URL. Read the ‘What is URL?’ section for the details and code.
  2. How to get base URL in JavaScript. Read the ‘How to get base URL in JavaScript?’ section for the details and code.
  3. How to get base from the current URL in JavaScript. Read the ‘How to get base from the current URL in JavaScript?’ section for the details and code.
  4. How to get URL origin in JavaScript. Read the ‘How to get URL origin in JavaScript?’ section for the details and code.
  5. How to get the base URL from a string in JavaScript. Read the ‘How to get the base URL from a string in JavaScript?’ section for the details and code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment