Hi Friends 👋,

Welcome To Infinitbility! ❤️

To replace string in node js, use the replace() and use replace() with /PUT_HERE_REPLACEABLE_STRING/g regex method.

  1. the replace() method replace your first occurrence ( match ) from your string
  2. the replace() method with regex will replace all occurrences from your string

Just you have to pass two parameters, in the first parameter you have to pass what you want to replace and in the second parameter you have to pass what you want to put in the place of replace string.

In the following example, we will take the samples string, and use both replace methods for replacing space with a hyphen ( - ).

let str = "hi friends welcome to infinitbility".

str.replace(" ", "-"); // "hi-friends welcome to infinitbility"

str.replaceAll(/ /g, "-"); // "hi-friends-welcome-to-infinitbility"

Today, I’m going to show you How do i replace strings in node js, as mentioned above here, I’m going to use the replace() or replace() method with regex.

Let’s start today’s tutorial how do you replace strings in node js?

In this node js example, we will do

  1. take an example of a string variable
  2. use the replace() or replace() method with regex
  3. example of replacing space with a hyphen
  4. example of replacing string with another string
  5. example of removing space from a string
  6. print the output in the node js console
var http = require("http");

//create a server object:
  .createServer(function (req, res) {
    let str = "hi boys hi girls welcome to infinitbility";

    // Example of replace space with hypen
    console.log("Example of replace space with hypen");
    let replaceSWH = str.replace(" ", "-");
    let replaceAllSWH = str.replace(/ /g, "-");


    // Example of replace string with another string
    console.log("Example of replace string with another string");
    let replaceSWS = str.replace("hi", "hello");
    let replaceAllSWS = str.replace(/hi/g, "hello");


    // Example of remove space from string
    console.log("Example of remove space from string");
    let replaceSWN = str.replace(" ", "");
    let replaceAllSWN = str.replace(/ /g, "");


      str +
        "\n\n" +
        replaceSWH +
        "\n" +
        replaceAllSWH +
        "\n\n" +
        replaceSWS +
        "\n" +
        replaceAllSWS +
        "\n\n" +
        replaceSWN +
        "\n" +
    res.end(); //end the response
  .listen(8080); //the server object listens on port 8080

In the above node js example, we have taken the sample string variable and performed an example of replacing space with a hyphen, replacing string with another string, and removing space from a string.

I hope it helps you, All the best 👍.