-2

I have two simple strings I want to output (both coming from user input). The console.log says that they are properly received by JavaScript into their respective variables, but when I output them via innerHTLM, the first is truncated at the "<" symbol.

JavaScript

var content1 = "Dog- Happy<Hungry", content2 = "Dog- Happy<2Hungry"
console.log(content1,content2)
document.getElementById("output").innerHTML = content1 + "<br>" + content2

Output

Dog- HappyDog- Happy<2Hungry

Expected Output

Dog- Happy<Hungry
Dog- Happy<2Hungry

The input is from users and I want them to be able to use the "<" symbol, as it is a common symbol for this type of input. I am guessing that the "<" is being seen as the beginning of an HTML tag, though I am not sure. How do I solve this, so that they can use the "<" symbol?

Here is a JSFiddle if it is helpful: https://jsfiddle.net/m79dca3p/

Encode html entities in javascript does not help as those responding are split on the best solution, thus it is still an open debate and not a solution.

Thomas
  • 438
  • 6
  • 14
  • 1
    Does this answer your question? [Encode html entities in javascript](https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript) – esqew Feb 11 '21 at 16:19
  • Consider using `<` instead of `<`? – evolutionxbox Feb 11 '21 at 16:21
  • @evolutionxbox — It's user input. – Quentin Feb 11 '21 at 16:21
  • @Quentin In that case the character could be swapped out? – evolutionxbox Feb 11 '21 at 16:22
  • I found this one that seems to be similar, also: https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript. Is that the recommended solution, to do a bunch of `.replace()` lines? – Thomas Feb 11 '21 at 16:26
  • @esqew It seems like people responding to that page are split on what to do. The first answer has over a hundred upvotes, but the second answer, likewise with many upvotes, says "The currently accepted answer has several issues." – Thomas Feb 11 '21 at 16:30

2 Answers2

4

< is how you start a tag in HTML, and since you use innerHTML the input is treated as HTML.

If you want input to be treated as plain text, use a mechanism that deals in text and not one that deals in HTML.

const content1 = "Dog- Happy<Hungry";
const content2 = "Dog- Happy<2Hungry";
const output = document.getElementById("output");
output.append(document.createTextNode(content1));
output.append(document.createElement('br'));
output.append(document.createTextNode(content2));
<div id=output></div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'm not familiar with `.append()`. Does it deal with these symbols correctly without having to swap them out? – Thomas Feb 11 '21 at 16:27
  • No. `createTextNode` does. You can see the result in the live demo in the answer. – Quentin Feb 11 '21 at 16:29
-3

Just use innerText instead of innerHTML and add your <br>separateley

inetphantom
  • 2,498
  • 4
  • 38
  • 61