English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js URL ParsingIn this tutorial, we will learn how to parse a URL or break down a URL into readable parts in Node.js, and use the built-in Node.js URL module to extract search parameters.
To parse a URL in Node.js: Use the url module, and with the help of parsing and query functions, you can extract all components of the URL.
This is a step-by-step guide on how to parse a URL into readable parts in Node.js and extract search parameters using the built-in Node.js URL module.
Step1Use the URL module
var url = require(‘url‘); |
The2Step: Bring the URL into the variable. The following is an example URL that we will analyze.
var address = ‘http://localhost:8080/index.php?type=page&action=update&id=5221‘; |
Step3Use the parsing function to parse the website address.
var q = url.parse(address,true); |
Step4: Use dot notation to extract HOST, PATHNAME, and SEARCH strings.
q.host q.pathname q.search |
Step5: Use query functionality to parse URL search parameters.
var qdata = q.query; |
The6Step: Access Search
qdata.type qdata.action qdata.id |
// Include the URL module var url = require('url'); var address = 'http://localhost:8080/index.php?type=page&action=update&id=5221'; var q = url.parse(address, true); console.log(q.host); //Returns 'localhost:8080' console.log(q.pathname); //Returns'/index.php' console.log(q.search); //returns '?type=page&action=update&id=5221' var qdata = q.query; // Returns an object: {Type: Page, Operation: 'update', id = '5221} console.log(qdata.type); //Returns "Page" console.log(qdata.action); //Returns "Update" console.log(qdata.id); //Returns " 5221"
Terminal Output
$ node urlParsingExample.js localhost:8080 /index.php ?type=page&action=update&id=5221 page update 5221
In this Node.js tutorial–Parse URL inWe learned how to use the built-in Node.js URL module to parse or split URLs into readable parts in Node.js. And extract the host, pathname, search, and search parameters.