How to Setup Regex for ExpressJS Router URL in Node.js ?
Last Updated :
08 Jan, 2025
ExpressJS Router is a class that acts as a middleware to provide route handling or determining how an application responds to a client requests, of various HTTP methods, to a particular URI.
Approach
Setting up regex for Express.js router URLs in Node.js involves defining custom patterns using regular expressions to match specific URL structures, enhancing flexibility and precision in route handling within your application.
Setting up regex for routing in Express.js enables flexible and dynamic URL matching.
Steps to Create Express App
Step 1: Create package.json using the following command:
npm init
Step 2: You can visit the link Install Express to see how to install the express module. You can install this package by using the command :
npm install express
Step 3: Create app.js, params.js, and routes.js files in the view folder. The project directory will look like this:
Project StructureSetting up Regex in URL
We can easily set up Regex for our Express Router by following these two points:
- To make our route match with a particular regular expression, we can put regex between two forward slashes like this /<routeRegex>/
- Since every route contain /, so wherever we have to use / inside Regex, use a backslash \ / before it.
Example: In the following code, we are setting up regex, for when HTTP get request is received to route /home, a response Homepage is rendered to the client.
router.get(/\/home/ , (req,res)=>{
res.send('Homepage');
)
Now create a routes.js file that will contain different requests for different routes using Regex.
Node
// routes.js
// Requiring module
const express = require('express');
const router = express.Router();
// Route which matches /abc or /adc
router.get(/\/a[b|d]c/, (req, res) => {
res.send("<h1>Route First</h1");
})
// Routes that matches /a(any single digit)/
// followed by 2 times c or 3 times c or
// /a(any single digit) / followed by 2
// times c or 3 times c
router.get(/\/a[0-9]\/c{2,3}/, (req, res) => {
res.send("<h1>Route Second</h1");
})
// Routes that ends with /Hello followed by
// a letter in [a-z] any no. of times and
// ends with "OK"
router.get(/^\/Hello[a-z]*OK$/, (req, res) => {
res.send('<h1>Route Third</h1>')
})
// Routes that must end with string "Hello"
// and can have any no. of any character
// before that
router.get(/\/*Hello$/, (req, res) => {
res.send('<h1>Route Fourth</h1>')
})
module.exports = router;
Setting up Regex in URL parameters
To set up Regex for URL parameters, we can provide regex inside parenthesis just after the name of the parameters. In the following file, we have implemented Regex for URL parameters.
Node
// params.js
// Requiring module
const express = require('express');
const router = express.Router();
// Setting up regex for name and contact parameters
router.get('/user/:name([a-zA-Z]+)/:contact([6-9][0-9]{9})', (req, res) => {
const name = req.params.name;
const contact = req.params.contact;
res.send({
"username": name,
"contact": contact
})
})
module.exports = router;
Node
// app.js
// Requiring modules
const express = require('express');
const app = express();
const router = express.Router();
const route = require('./routes');
const param = require('./params');
// Using routers as middleware to
// use route.js and params.js
app.use('/', route);
app.use('/', param);
// Starting server on port 8000
app.listen(8000, () => {
console.log("Server is listening on port 8000");
})
Step to run the application: Run the app.js file using the following command.
node app.js
Output:
- Showing the functioning of all the routes defined in the routes.js file.
- Showing the functioning of the routes defined in the params.js file.
Similar Reads
How to filter path of routes in Express.js ? Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will be discussing how to filter the paths of routes using the express.js in node.js. The ap
2 min read
Build Your First Router in Node.js with Express Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, how to use the router in the express.js server.The express.Router() function i
2 min read
How do you handle nested routes in Express.js? In this article we are going to learn that how can we setup nested routes in Express JS. Nested routes are the routes that are defined within other routes. This is used to organize your code.We are going to implement the nested routes using the below given two approaches.Table of ContentUsing Expres
2 min read
How to do Templating using ExpressJS in Node.js ? Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article w
2 min read
How to Retain Special Characters in ExpressJS Router URL Request ? Retaining special characters in Express.js router URL requests involves ensuring that URLs are correctly encoded and decoded, and configuring your Express application to handle these characters appropriately. Special characters, such as @, #, ?, &, +, etc., need to be properly encoded when used
2 min read