How to remove html tags from string in react js

I have multiple whole html code in variable cleanHTML and i need to strip specific tags from text.

let cleanHTML = document.documentElement.outerHTML

this:

please
me too
and me

to this:

please
me too
and me

I´m trying to do it with:

var list = cleanHTML.getElementsByClassName["remove-me"];
var i;
for [i = 0; i < list.length; i++] {
  list[i] = list[i].innerHTML;
}

But i´m getting error from React cleanHTML.getElementsByClassName is not a function

Any idea how to do it in a way React likes?

asked Sep 10, 2018 at 12:38

Radek MezuláníkRadek Mezuláník

3011 gold badge5 silver badges14 bronze badges

2

Your cleanHtml is a string and not a node. So getElementsByClassName does not apply as it is not a string function

You can use regular expressions to do this. Following code might help.

var stripedHtml = cleanHtml.replace[/]+>/g, ''];

And stripedHtml will have your html content without tags.

answered Sep 10, 2018 at 12:51

1

I am guessing from your specification that your cleanHTML is a string, so you would need to convert the string to a node [eg: by creating a div from it], and then parsing the nodes appropriately.

Please note that you really need to request the textContent and not the innerHTML, as you do not want to have any html in your react output

const htmlContent = `please
me too
and me`;

const getNodesToRemoveFromElement = [stringContent] => {
  const el = document.createElement['div'];
  el.innerHTML = stringContent;
  return el.getElementsByClassName['remove-me'];
};

for [let node of getNodesToRemoveFromElement[ htmlContent ] ] {
  console.log[ node.textContent ];
}

answered Sep 10, 2018 at 12:46

IcepickleIcepickle

12.5k3 gold badges33 silver badges46 bronze badges

Posted Mahedi Hasan Category JavaScript Published June 15, 2021

Hello devs in this example i am going to share the source code of how you can remove html tag from your string. So in this javascript strip html tag example code tutorial you will learn javascript remove html tags from string regex.

If you don't know that way of removing html tags from string javascript then this tutorial is for you. We can do it many ways but i am going to share the most and very easy way using a single line of code with regex.

Example code:


                      
                      
                  

Comments

  1. Your script works great! Cheers!

  2. this is so cool , i like it

  3. function strip[html]
    {
    var tmp = document.createElement["DIV"];
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText;
    }

Leave a Reply

How do I remove text tags in HTML?

Removing HTML Tags from Text.
Press Ctrl+H. ... .
Click the More button, if it is available. ... .
Make sure the Use Wildcards check box is selected..
In the Find What box, enter the following: \[[!

Chủ Đề