Skip to content
Related Articles

Related Articles

Improve Article

How to join all given URL segments together in jQuery ?

  • Last Updated : 01 Jul, 2021
Geek Week

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.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
  
    <script src=
    </script>
</head>
  
<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>
  
    <script>
          
        // 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
            res.join('/');
  
            var init = "";
            for (var i = 0; i < res.length; i++) {
                init += res[i];
            }
            var temp1 = init.replace(/[\/]+/g, '/')
  
            // Regex for mathcing 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('&', '?');
  
            $("#display").html(
                "Joined URL is as follows:-" + finalres);
        }
    </script>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :