Explain Codes LogoExplain Codes Logo

How do I properly escape quotes inside HTML attributes?

html
html-escaping
attribute-values
security-best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 30, 2024
TLDR

Replace double quotes with " and single quotes with ' in HTML attributes:

<a href="#" title="Bob&#39;s &quot;Burger Shack&quot;">Click here</a>

This approach guarantees attribute values are correctly interpreted without any syntax disruption.

Escaping in different languages

If you're encoding attribute values via a programming language, there are several methods available:

  • PHP: Use htmlentities() or htmlspecialchars() functions:

    echo '<input type="text" name="example" value="' . htmlspecialchars($userInput, ENT_QUOTES) . '">';
  • JavaScript: Libraries like Lodash offer the _.escape() function:

    let safeAttribute = _.escape(userInput);

Single versus double quotes for better legibility

Another strategy is to use single quotes to separate markup and event handlers or injected strings:

<button type='button' onclick='alert("Button clicked!")'>Click me</button>

This decision can add clarity to your code and improve readability.

Assessing functionality after escaping: crucial test cases

It's vital to test your code after implementing escaping techniques. Here are some crucial test cases:

  • Dropdown menus should retain their value on a postback.
  • Event handlers like onclick should execute correctly without syntax errors.
  • Any data-bound values should reflect escaped values.

Handling of JavaScript-generated HTML

Quotes within JavaScript-generated HTML need to adhere to JavaScript's own rules of string escaping:

let title = "Bob's \"Burger Shack\""; let linkHTML = `<a href="#" title="${title.replace(/"/g, '&quot;').replace(/'/g, '&#39;')}">Click here</a>`;

Security angle: data handling

Proper escaping helps to bullet-proof data handling security:

  • Escaped attributes aren't susceptible to injection attacks.
  • Always use methods recommended by recognized standards.
  • Periodically review your code for attributes that might require escaping.