Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To remove html tags from string in react js, just use the /(<([^>]+)>)/ig regex with replace() method it will remove tags with their attribute and return new string.

Let’s do some example

Take sample html string, remove their tags using /(<([^>]+)>)/ig regex with replace() method.

const htmlStr = "<h1>Infinitbility, </h1><p>We have the ability to build infinite way for us.</p>";

const newStr = htmlStr.replace(/(<([^>]+)>)/ig, '');

// 👇️ 'Infinitbility, We have the ability to build infinite way for us.'
console.log(newStr);

Today, I’m going to show you How do I remove html tags from string in react js, as above mentioned here, I’m going to use the /(<([^>]+)>)/ig regex with replace() method to delete html tags from string.

Let’s start today’s tutorial how do you remove html tags from string in react js?

In this example, we will do

  1. create sample html string state
  2. use the /(<([^>]+)>)/ig regex with replace() method to replace html with empty string
  3. print removed html tags string in a screen

Let’s write code…

import React, { useState, useEffect } from "react";
export default function App() {
    const [string, setString] = useState('<h1>Infinitbility, </h1><p>We have the ability to build infinite way for us.</p>');

     useEffect(() => {
        const regex = /(<([^>]+)>)/ig;
        const newString = string.replace(regex, '');
        setString(newString);
    }, []);

  return (
    <div className="App">
      <p>{string}</p>
    </div>
  );
}

As mentioned above, we are taken the example of a html string state, remove tags from string on page load and printed output in the screen.

I hope it’s help you, All the best 👍.