JavaScript: Extracting ID from URL – Splitting Strings

How to extract an ID from a given URL in Node JS App? Get ID from GET request in node js app. Splitting a string based on a character and extracting the last part.

Extracting ID from a JavaScript URL

Splitting String in JavaScript Example Code

module.exports = (req, res) => {
    let id = req.url.split("/")[3];

   //url = http://localhost:5000/api/movies/125566
   //id= 125566

    if(req.url === "/api/movies") {
        res.statusCode = 200;
        res.setHeader("Content-Type", "application/json");
    } else {
        res.writeHead(404, {"Content-Type": "application/json" });
        res.end(JSON.stringify({ title: "Not Found", message: 'Route not found'}))



Here in the above-given example, the code will be extracting the ID from the URL in the node JS app. Here we have used the javascript split function to split and extract the ID. So the id can be used for processing the GET request in the API code.

Reference: JavaScript Split Function

So in this smartcodehelper post, we had seen an example of using the split function in javascript.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *