Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To replace string in react js, use the replace() or replaceAll() method.

  1. the replace() method replace your first occurrence ( match ) from your string
  2. the replaceAll() method 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(" ", "-"); // "hi-friends-welcome-to-infinitbility"

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

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

In this example, we will do

  1. take an example of a string state
  2. use the replace() or replaceAll() method
  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 of the string on the page screen
import React, { useState, useEffect } from "react";
export default function App() {
  const [sampleString, setSampleString] = useState(
    "hi boys hi girls welcome to infinitbility"
  );

  return (
    <div className="App">
      <h1>{`Example of replace space with hypen`}</h1>
      <p>{sampleString.replace(" ", "-")}</p>
      <p>{sampleString.replaceAll(" ", "-")}</p>

      <h1>{`Example of replace string with another string`}</h1>
      <p>{sampleString.replace("hi", "hello")}</p>
      <p>{sampleString.replaceAll("hi", "hello")}</p>

      <h1>{`Example of remove space from string`}</h1>
      <p>{sampleString.replace(" ", "")}</p>
      <p>{sampleString.replaceAll(" ", "")}</p>
    </div>
  );
}

In the above react js example, we have taken the sample string state, 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 đź‘Ť.