-1

I have found a similar post, but my situation is different and I think others could benefit if it's in a different post. My problem is that I have a textarea where people can type anything. I put all the text from the textarea into a variable called "input1" where it is then put into a div to show what the user has typed. my problem is if the user types HTML in the textarea, it will show the HTML in the div. What I have tried is putting the textarea text into the variable "input1" that my system can use, but then from "input1" into "input2" variable, but as a formatted version of the HTML code that will display the HTML but not run it. So if the user types this:

<strong>example text</strong>

I would like it to show this:

<strong>example text</strong>

Not this:

example text

Haydan Fisher
  • 73
  • 2
  • 5
  • 1
    replace all `<` and `>` by `<` and `>`. – Sirko Dec 15 '20 at 20:41
  • Please provide the code that you already have. By the sound of it, you're setting innerHtml while you should do something else like produce a div with ``` font-family: monospace; white-space: pre; ``` and have input1 value inside – dehumanizer Dec 15 '20 at 20:41
  • Does this help? https://stackoverflow.com/questions/40263803/native-javascript-or-es6-way-to-encode-and-decode-html-entities – Txema Dec 15 '20 at 20:41
  • Check out the ```encodeuri()``` and ```decodeuri()``` functions in javascript. – Stephen Taylor Dec 15 '20 at 20:42
  • You can check the answers on this question, it explained in detail: https://stackoverflow.com/questions/2820453/display-html-snippets-in-html – Mikail Bayram Dec 15 '20 at 20:43
  • How do you "inject" the user's input to your ```div```? you can just use ```userInputToShowDiv.innerHTML = userInputText``` – Two Horses Dec 15 '20 at 20:44
  • I should have given my code, but its kindof sloppy and has many other things in it. I should also have added that the div still needs to be able to display html, just that the string should not have anything that displays html. I think I understand @Sirko about replacing all the < and > with those, I think I should also change &. is there anything else I would replace using input2 = input1.replace(//g, ">").replace(/&/g, "&") – Haydan Fisher Dec 15 '20 at 20:53
  • There's no need to replace anything, as the answers to the linked question shows. – Heretic Monkey May 26 '21 at 23:31

1 Answers1

0

Thank you @Sirko for pointing me in the right direction, I used what you sent me. Using what I now know I have changed my variables to work. This is a sample of what I did.

input1 = input2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g,'&gt;')

I have found that you should change the & first, then < and >. because otherwise, it will change the text to a &lt; then to a &amp;lt;.

Haydan Fisher
  • 73
  • 2
  • 5