Node.js URL – Parse or Split a URL into readable parts in Node.js

In this tutorial, we shall learn how to parse or split a URL into readable parts in Node.js and extract search parameters using built-in Node.js URL module.

Split a URL into readable parts in Node.js using Node.js URL module

Following is a step-by-step guide to program on how to split a URL into readable parts in Node.js.

  • Step 1 : Include URL module
    var url = require(‘url‘);
  • Step 2 : Take URL to a variable
    Following is a sample URL that we shall parse.

    var address = ‘http://localhost:8080/index.php?type=page&action=update&id=5221‘;
  • Step 3 : Parse URL using parse function.
    var q = url.parse(address, true);
  • Step 4 : Extract HOST, PATHNAME and SEARCH string using dot operator.
    q.host
    q.pathname
    q.search
  • Step 5 : Parse Search Parameters using query function.
    var qdata = q.query;
  • Step 6 : Access Search Parameters
    qdata.type
    qdata.action
    qdata.id

Complete Node.js program to parse a URL into readable parts in Node.js

 

Conclusion :

In this Node.js Tutorial, we have learnt how to parse or split a URL into readable parts in Node.js using built-in Node.js URL module. And extract host, pathname, search and search parameters.