Languages
[Edit]
EN

JavaScript - how to escape html special characters?

8 points
Created by:
Imaan-Morin
1009

In this article, we would like to show how to escape special HTML characters using JavaScript.

Escape special HTML characters in JavaScript
Escape special HTML characters in JavaScript

Quick solution (check section 1 to see working in Node.js version):

 

Custom function example - based on replace method

Edit

In this section presented solution replaces special HTML characters with codes (check characters list here).

Note: this solution works under Node.js. 

 

innerText property example

Edit

By setting the text on the element using innerText and getting it back with innerHTML we are able to escape special HTML characters.

Note: by default, this approach doesn't work under Node.js because the DOM is not supported there (required additional libraries).

 

textContent property example

Edit

By setting the text on the element using textContent and getting it back with innerHTML we are able to escape special HTML characters.

Note: by default, this approach doesn't work under Node.js because the DOM is not supported there (required additional libraries).

 

Container element-based approach examples

Edit

The below examples use the same techniques using stored in the memory element.

3.1. Text node and innerHTML property-based example

Edit

3.2. innerText and innerHTML properties based example

Edit

 

See also:

Edit
  1. HTML - characters that should be escaped 
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join