Categories
JavaScript Answers

How to encode a string in JavaScript for displaying in HTML?

Spread the love

Sometimes, we want to encode a string in JavaScript for displaying in HTML.

In this article, we’ll look at how to encode a string in JavaScript for displaying in HTML.

How to encode a string in JavaScript for displaying in HTML?

To encode a string in JavaScript for displaying in HTML, we create a text node.

For instance, we write

document.body.appendChild(document.createTextNode("foo<bar>baz"));

to call createTextNode to create a text node with the text.

Then we call document.body.appendChild to append the text= node as the last child of the body element.

Conclusion

To encode a string in JavaScript for displaying in HTML, we create a text node.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *