Node.js Parse URL

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

Node Parse URL

To parse URL in Node.js : use url module, and with the help of parse and query functions, you can extract all the components of URL.

Node.js Parse URL components – Step by step guide

Following is a step-by-step guide to program on how to parse 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 URL 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 TutorialParse URL, 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.