Skip to main content
Home/Blog/Web Development/How Do I Encode HTML in JavaScript and Other Programming Languages?
Web Development

How Do I Encode HTML in JavaScript and Other Programming Languages?

Learn the proper methods and best practices for encoding HTML across JavaScript, Python, PHP, and other popular programming languages to prevent XSS attacks.

By Inventive HQ Team•
How Do I Encode HTML in JavaScript and Other Programming Languages?

The Critical Importance of HTML Encoding

To encode untrusted data for HTML text or a quoted ordinary text attribute, escape characters that have special meaning in that context at output time. Common escapers handle &, <, and >, while quote handling varies by function and context. For explicit quote encoding, the entities include &quot; and &#39;. Examples include textContent or a regex in JavaScript, html.escape() in Python, htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') in PHP, OWASP Encode.forHtml() in Java, html.EscapeString() in Go, and WebUtility.HtmlEncode() in C#. Escaping HTML text prevents an attacker's <script> from being parsed as a tag; other output contexts need their own protections.

That's the summary an AI Overview will give you. What it can't show you is which control to use where — because "HTML encoding" is one of several context-specific protections, and applying the right function in the wrong place (HTML entity encoding inside a <script> block, for example) leaves the hole wide open. Below is a per-language cheat sheet, a decision diagram for picking the right control by output context, and a live encoder you can paste payloads into to see exactly what each function does.

HTML Entity Encoder & Decoder

Encode and decode HTML entities online with XSS prevention analysis. Supports named and numeric entities.

Open the full HTML Entity Encoder & Decoder tool →
Loading interactive tool...

The Five Characters, and Why Context Beats Syntax

Before the language-by-language tour, consider where the data will land. Each destination parses input differently, so the required escaping or validation depends on the output context.

Choosing the right encoding by output context Untrusted input branches to HTML body, HTML attribute, JavaScript, URL, and CSS contexts. URLs also need scheme validation; CSS values need property-specific validation. Untrusted input "Where does it land?" HTML body <div>HERE</div> HTML entity escape &<> HTML attr value="HERE" Entity + quotes ENT_QUOTES JavaScript var x="HERE" NOT HTML enc JS string escape URL ?q=HERE Percent-encode encodeURIComponent CSS color: HERE Validate value fixed property The trap HTML entities are not decoded inside <script> raw text: use JavaScript-safe serialization for values in scripts. Right function, wrong context = still exploitable.

For the CSS branch, keep the property name fixed and restrict the value to an allowed form for that property. CSS escaping by itself does not establish that an arbitrary declaration value is acceptable. For a complete URL in href, validate its scheme and destination before encoding it for the quoted HTML attribute.

HTML Encoding in JavaScript

JavaScript provides several methods for encoding HTML, each suited to different use cases and contexts. As one of the most widely used programming languages in web development, mastering HTML encoding in JavaScript is particularly important.

Native Browser Methods

Modern browsers provide built-in DOM methods for HTML encoding. The most reliable approach uses the textContent property of DOM elements:

function encodeHTML(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

This method uses the browser's HTML serialization for a text node. It escapes characters needed to keep the text from being parsed as markup, but the resulting innerHTML may leave quotes unchanged. Use a context-appropriate encoder when placing data in an attribute or another output context.

Manual Character Replacement

For environments where DOM manipulation is not available, such as Node.js, you can implement manual character replacement:

function encodeHTML(str) {
  return str.replace(/[&<>"']/g, function(match) {
    const encode = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;'
    };
    return encode[match];
  });
}

This approach explicitly replaces each dangerous character with its HTML entity equivalent. With sequential replacement calls, encode ampersands first to avoid double-encoding. The single-pass regex example replaces each input character only once.

URL Encoding in JavaScript

When dealing with URLs, JavaScript provides dedicated functions:

const encoded = encodeURIComponent(userInput);
const decoded = decodeURIComponent(encoded);

The encodeURIComponent() function encodes a URL component, which is different from HTML entity encoding. Use it for an untrusted query value or path segment within a URL whose scheme and destination are permitted. It does not validate a complete URL. When writing the URL into HTML markup, also encode it for the quoted attribute.

Template Literals and Security

ES6 template literals do not automatically encode HTML. This common misunderstanding leads to vulnerabilities:

// Vulnerable - does NOT encode
const html = `<div>${userInput}</div>`;

// Secure - must encode explicitly
const html = `<div>${encodeHTML(userInput)}</div>`;

Modern frameworks like React escape values rendered as JSX text, but when using template literals for HTML generation, encode each untrusted interpolation for its destination context. The example above places data in HTML text; attributes, URLs, scripts, and styles need context-specific handling.

HTML Encoding in Python

Python offers multiple approaches to HTML encoding, with built-in libraries and established third-party packages providing robust solutions.

Using the html Module

Python's standard library includes the html module with straightforward encoding capabilities:

import html

# Encode HTML entities
encoded = html.escape(user_input)

# With quote encoding
encoded = html.escape(user_input, quote=True)

# Decode HTML entities
decoded = html.unescape(encoded)

The html.escape() function converts special characters to HTML entities. The quote parameter determines whether to encode quote characters, which is essential when inserting data into HTML attributes.

String Encoding Methods

Python strings have an encode() method for character encoding, though this serves a different purpose than HTML entity encoding:

# Character encoding (not HTML entity encoding)
byte_string = text.encode('utf-8')
text = byte_string.decode('utf-8')

This encodes the string to bytes using a specific character encoding like UTF-8, which is different from HTML entity encoding used for XSS prevention.

Third-Party Libraries

For user-supplied markup that should retain selected tags, bleach provides HTML sanitization:

import bleach

# Sanitize while allowing specific tags
clean = bleach.clean(user_input, tags=['p', 'b', 'i'], strip=True)

bleach.clean() sanitizes an HTML fragment for an HTML content context; it is not a general-purpose output encoder for attributes, scripts, styles, or URLs. For plain text, use html.escape().

HTML Encoding in PHP

PHP has been a staple of web development for decades, and it provides robust built-in functions for HTML encoding.

The htmlspecialchars Function

PHP's htmlspecialchars() is a built-in function for HTML encoding:

$encoded = htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

This function converts special characters to HTML entities. The parameters are crucial:

  • ENT_QUOTES: Encodes both double and single quotes
  • ENT_SUBSTITUTE: Replaces invalid UTF-8 sequences instead of returning an empty string
  • 'UTF-8': Specifies the character encoding to use

Using ENT_QUOTES is essential because failing to encode quotes allows attackers to break out of HTML attributes and inject malicious code.

The htmlentities Function

For more comprehensive encoding, PHP offers htmlentities():

$encoded = htmlentities($userInput, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');

This function encodes characters with HTML entity equivalents beyond the five handled by htmlspecialchars(). The ENT_HTML5 flag selects HTML5 entity handling.

Context-Specific Encoding

PHP also provides URL encoding functions:

$urlEncoded = rawurlencode($userInput);
$urlEncoded = urlencode($userInput);

The difference is subtle: rawurlencode() follows RFC 3986, while urlencode() is designed for query strings and encodes spaces as + instead of %20.

HTML Encoding in Other Languages

Java

Java applications often use libraries like the OWASP Java Encoder:

import org.owasp.encoder.Encode;

String safe = Encode.forHtml(userInput);
String safeAttr = Encode.forHtmlAttribute(userInput);
String safeJs = Encode.forJavaScript(userInput);

This library provides context-specific encoding methods, ensuring the appropriate encoding for where the data will be rendered.

Ruby

Ruby on Rails includes automatic HTML encoding in views:

<%= user_input %>  # Automatically encoded
<%== user_input %> # Raw output, not encoded

For manual HTML encoding, use ERB::Util.html_escape. Calling html_safe marks a string as safe and can bypass escaping, so do not use it to encode untrusted input:

require 'erb'
encoded = ERB::Util.html_escape(user_input)

C# and ASP.NET

The .NET framework provides the HttpUtility and WebUtility classes:

using System.Web;
string encoded = HttpUtility.HtmlEncode(userInput);

// Or in .NET Core
using System.Net;
string encoded = WebUtility.HtmlEncode(userInput);

ASP.NET MVC and Razor views automatically encode output by default using the @ symbol, while @Html.Raw() bypasses encoding.

Go

Go's html/template package automatically encodes template values:

import "html/template"

tmpl := template.Must(template.New("page").Parse("<div>{{.}}</div>"))
tmpl.Execute(writer, userInput) // Automatically encoded

For manual encoding, use the html.EscapeString() function:

import "html"
encoded := html.EscapeString(userInput)

Per-Language Cheat Sheet: Which Function, Which Flag

One row per language. The "gotcha" column is where the real bugs live — the default that silently leaves quotes unencoded, or the function that looks like an HTML escaper but isn't one.

LanguageHTML-body encoderAuto-escaping in templates?The gotcha to remember
JavaScript (browser)el.textContent = x; el.innerHTMLNo (template literals are raw)Assigning untrusted raw markup to innerHTML or dangerouslySetInnerHTML is risky; properly encoded or sanitized HTML can be appropriate
JavaScript (Node)regex replace & < > " 'NoA single-pass regex avoids double-encoding generated entities
Pythonhtml.escape(x)Django yes; standalone Jinja2 requires autoescape configurationPass quote=True (default) for quoted attributes
PHP`htmlspecialchars($x, ENT_QUOTESENT_SUBSTITUTE, 'UTF-8')`No (raw echo)
JavaEncode.forHtml(x) (OWASP)Plain JSP EL no; Thymeleaf th:text escapesUse <c:out> or an explicit encoder for JSP EL output
Ruby / RailsERB::Util.html_escape(x)ERB <%= %> yes.html_safe and <%== %> disable escaping
C# / .NETWebUtility.HtmlEncode(x)Razor @ yes@Html.Raw() bypasses; HttpUtility needs System.Web
Gohtml.EscapeString(x)html/template yes (contextual)text/template does NOT escape — easy to grab the wrong one
Which should I use?Prefer the framework's auto-escaper where it applies—Use an explicit encoder when generating HTML outside a template

Across these languages, use a framework's contextual auto-escaper where it applies, and use an explicit encoder when building HTML by hand. Check the actual template mechanism: plain JSP EL, Go's text/template, and JavaScript template literals do not HTML-escape interpolated values by default.

Best Practices Across All Languages

Regardless of the programming language you use, several universal best practices apply to HTML encoding.

Use Framework Built-Ins

Modern web frameworks typically include automatic HTML encoding. React escapes JSX text values, Angular performs contextual escaping, Django auto-escapes template variables by default, and Rails encodes ERB output. Prefer these built-in protections where they apply, and check how the framework handles the destination context.

Encode at Output Time

Perform encoding immediately before outputting data to the user, not when storing it in the database. Storing encoded data creates problems when the same data needs to be displayed in different contexts or used in non-HTML formats like JSON or PDF.

Context-Sensitive Encoding

Different contexts require different encoding methods:

  • HTML content: HTML entity encoding
  • HTML attributes: HTML entity encoding with quotes
  • JavaScript: JavaScript string encoding
  • URLs: Validate complete URLs; percent-encode untrusted components and encode the completed URL for its HTML attribute when needed
  • CSS: Keep property names fixed and validate values against the allowed form for each property

Using the wrong encoding for a context can be ineffective or even introduce new vulnerabilities.

Never Trust Client-Side Encoding

Encode untrusted data for its output context wherever rendering happens. Server-rendered output needs server-side encoding; client-rendered DOM output needs safe DOM APIs or context-aware encoding.

Use Established Libraries

Use a maintained output encoder, such as an OWASP encoder or your framework's built-in escaping, for plain data in the appropriate context. When users are allowed to supply HTML markup, a sanitizer such as DOMPurify can remove disallowed markup; it does not replace context-appropriate output encoding.

Common Pitfalls to Avoid

Double Encoding

Encoding data multiple times can cause display issues:

// Wrong - double encoded
const bad = encodeHTML(encodeHTML(userInput));
// Result: &amp;lt;script&amp;gt; instead of &lt;script&gt;

Avoid encoding data that has already been encoded. This often happens when encoding is performed at multiple layers of an application.

Incomplete Character Sets

For HTML text and quoted ordinary text attributes, encoding only < and > is insufficient. Account for:

  • Ampersands & (encode first when using sequential replacement passes)
  • Double quotes "
  • Single quotes '

An HTML text encoder does not need to encode forward slashes. Other parsers and output contexts have their own rules; use an encoder designed for the actual destination.

Wrong Encoding Function

Using encodeURI() instead of encodeURIComponent() in JavaScript is a common mistake. The former does not encode characters like = and & which are significant in query strings.

Mixing Encoding and Validation

Validation checks data format and content, while output encoding keeps data from being interpreted as syntax in a supported context. Use the controls required by the destination; validation alone does not replace context-appropriate output handling.

Testing Your Encoding

To verify your encoding implementation works correctly, test with these common XSS payloads:

<script>alert('XSS')</script>
"><script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
javascript:alert('XSS')
<svg onload=alert('XSS')>

When inserted as HTML text with HTML text encoding, these inputs should display as text rather than execute. Test each destination separately: URL values need scheme validation and component encoding, while script, style, and attribute contexts require their own controls. HTML entity encoding alone does not make these inputs safe in every context. Automated security testing tools can help identify failures across your application.

Performance Considerations

HTML encoding adds minimal performance overhead in most applications. However, in high-performance scenarios, consider:

  • Caching rendered output when the same data is displayed repeatedly in the same output context, with the context and encoding policy included in the cache key
  • Using streaming encoding for large documents
  • Leveraging framework-level caching mechanisms
  • Avoiding a second encoding pass over a value already encoded for that same context

The security benefits of proper encoding far outweigh any minor performance costs.

Conclusion

HTML encoding is a fundamental skill for web developers across all programming languages. While the specific syntax varies between JavaScript, Python, PHP, and other languages, the principles remain consistent: encode all untrusted data before displaying it, use context-appropriate encoding methods, leverage framework built-ins, and follow established best practices.

By mastering HTML encoding in your chosen programming language and understanding the common pitfalls to avoid, you can significantly reduce the risk of XSS vulnerabilities in your applications. Remember that encoding is just one layer in a comprehensive security strategy that should also include input validation, Content Security Policy, and regular security testing.

The web development landscape continues to evolve, but the need for proper HTML encoding remains constant. Stay informed about security best practices, keep your dependencies updated, and always prioritize security in your development workflow.

Need Expert Web Development?

From React to full-stack applications, our team builds modern, secure, and performant web solutions that scale with your business.