Code With Mark
Home
About
Resources
Contact

Easily Parse Any URL Address With Javascript

Does your website project have the need to parse url addresses? Or do you want to easily search through query string parameters from a URL?

There will come a time when you will have to know a url’s :

  • Protocol
  • Subdomain
  • Domain
  • Host
  • Parent Domain
  • TLD
  • Path
  • All of its query parameters

Let’s assume you want to parse below url:

https://demo.codewithmark.com/contact?id=123&name=mark

Its components would be:

  • Protocol: https
  • Domain: demo.codewithmark.com
  • Host: codewithmark
  • Parent Domain: codewithmark.com
  • TLD: com
  • Path : contact?id=123&name=mark
  • Query String: id=123&name=mark

 

When You Should Parse URL

This url parsing will come in handy when you need to collect data from query string on page load for your client’s campaign ad to see how well it is doing.

Or

If you have a multi-user WordPress site and you want to add “nofollow” to all the external links.

 

Javascript Parse URL Function

function parseURL(url)
{
    parsed_url = {}

    if ( url == null || url.length == 0 )
        return parsed_url;

    protocol_i = url.indexOf('://');
    parsed_url.protocol = url.substr(0,protocol_i);

    remaining_url = url.substr(protocol_i + 3, url.length);
    domain_i = remaining_url.indexOf('/');
    domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;
    parsed_url.domain = remaining_url.substr(0, domain_i);
    parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);    

    domain_parts = parsed_url.domain.split('.');   

    switch ( domain_parts.length )
    {
        case 2:
          parsed_url.subdomain = null;
          parsed_url.host = domain_parts[0];
          parsed_url.tld = domain_parts[1];
          break;
        case 3:
          parsed_url.subdomain = domain_parts[0] == 'www' ?  null : domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2];
          break;
        case 4:
          parsed_url.subdomain = domain_parts[0] == 'www' ?  null : domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];
          break;
    }

    parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;


    function getUrlVars(url) 
    {   
        var decodedUrl = decodeURIComponent(url);
        var any_param = decodedUrl.indexOf('?'); 
        if(any_param >  0)
        {
             any_param = decodedUrl.slice(decodedUrl.indexOf('?') + 1);
            var hashes = any_param.split('&');
            
            var merged = {};
            var hash;        

            for(var i = 0; i < hashes.length; i++) 
            {
                var res = {};
                hash = hashes[i].split('=');  

                if(hash.length > 0)
                {
                    res[hash[0]] = hash[1];
                    Object.assign(merged, res );
                }
            }            
            if(hashes.length > 0)
            {
                return merged;    
            }
        }
        else
        {
            return null; 
        }
    }

    return Object.assign(parsed_url, {qry_str : getUrlVars(url)});
}

Below is the components of: https://demo.codewithmark.com/contact?id=123&name=mark

Demo

Once you click away from the above, below it will show components of your url

How To Use The URL Parser Function:

<script type="text/javascript">


var url = parseURL('https://demo.codewithmark.com/contact?id=123&name=mark');

//out put
console.log(url.domain) //demo.codewithmark.com

console.log(url.host) //codewithmark

console.log(url.qry_str.id) //123
 
</script>
 

For Web Developers

Why Are You Still Getting Paid Only Once?

You spend weeks building a project.

Your client pays you.

Then the income stops.

Meanwhile, other developers are turning similar skills into products that generate revenue month after month.

A SaaS, plugin, web app, or digital product can continue bringing in customers long after it's launched.

The real question isn't whether you can build one.

It's how much money you're leaving on the table by not starting.

Learn How To Build Monthly Income →
how to easily create a basic web pagehow to easily create a basic web page←Previous
Beginner's Guide to node jsBeginner's Guide to node jsNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Form Validation in 1 Line

Top Posts Viewed

Google Sheets Timesheet Website App Script
1.81K views
Learn To Create YouTube Video Downloader
1.31K views
Easily Edit HTML Table Rows Or Cells With jQuery
910 views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress