Skip to content
Related Articles

Related Articles

How to join all given URL segments together in jQuery ?

Improve Article
Save Article
  • Last Updated : 01 Feb, 2022
Improve Article
Save Article

In this article, we will see how to join all given URL segments together using JavaScript. URL (Uniform Address Locator) consists of several segments, and these segments are listed below:

  • Scheme — It defines the protocol to be used to access the internet.
  • Domain name — It defines the hostname that holds the resource.
  • File Path — It defines the specific resource in the host you want to access.
  • Parameters — It is used to provide a string of information to be used.

In JavaScript, we can use regex to identify which part of the URL is provided to us, and accordingly that we can join all segments together. Let us look at an example to understand how we can join all given URL segments together.



<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
    <script src=
<body style="text-align:center">
<p>URL Joiner</p>
<p>Enter the domain name</p>
    <input type="text" name="domain" id="domain"><br>
<p>Enter the path name</p>
    <input type="text" name="path" id="path"><br>
<p>Enter parameter 1 name</p>
    <input type="text" name="parameter1" id="parameter1"><br>
<p>Enter parameter 2 name</p>
    <input type="text" name="parameter2" id="parameter2"><br>
    <button id="b1" onclick="urljoin()">Join URL</button>
    <div id="display"></div>
        // Function to join segments of URL
        function urljoin() {
            var domain = ($("#domain").val());
            var path = ($("#path").val());
            var parameter1 = ($("#parameter1").val());
            var parameter2 = ($("#parameter2").val());
            var res = [domain, path, parameter1, parameter2];
            // Joining each part of domains and appending
            // / after the end of each part
            var init = "";
            for (var i = 0; i < res.length; i++) {
                init += res[i];
            var temp1 = init.replace(/[\/]+/g, '/')
            // Regex for matching domain
            var temp2 = temp1.replace(/^(.+):\//, '$1://')
            var temp3 = temp2.replace(/^f:/, 'f:/')
            var temp4 = temp3.replace(/\/(\?|&|#[^!])/g, '$1')
            // Regex for joining different search parameters
            var temp5 = temp4.replace(/\?/g, '&')
            var finalres = temp5.replace('&', '?');
                "Joined URL is as follows:-" + finalres);


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!