How to escape string from PHP for javascript?

How to escape string from PHP for javascript?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Escape Strings for JavaScript in PHP

When building dynamic interfaces like a form editor where users can edit values, you inevitably face the tension between data integrity and code safety. The scenario you described—a value containing a double quote breaking an onclick attribute—is a classic symptom of incorrect context handling. You are not simply escaping characters; you are escaping for a specific output context: JavaScript inside HTML.

The core issue in your example is that addslashes() and mysql_real_escape_string() operate on SQL contexts, not JavaScript contexts. They escape single quotes for database queries or backslashes for string literals, but they fail to handle the structural requirements of embedded JavaScript. When you inject a raw string like aaaa"aaa into an attribute value, it terminates the string prematurely in the browser's parser, allowing subsequent code to execute in an unintended context. This is why your HTML looks broken even if the underlying data is valid.

Using json_encode() is often a safe fallback for arbitrary data, but as you discovered, it is not always the silver bullet when embedding values directly into DOM attributes. The screenshot you shared showing Firefox rendering a "bad" double quote likely stems from how the browser parses the HTML source versus the rendered object model. If you are outputting JSON directly to a <script> tag, json_encode works perfectly because it handles escaping for JavaScript string literals automatically. However, if you are injecting that data into an attribute like onclick="...", the surrounding quotes and the attribute delimiters introduce a new layer of complexity that json_encode does not resolve on its own when mixed with HTML attributes.

The robust solution is to use PHP's built-in htmlspecialchars() function specifically configured for JavaScript contexts. While htmlspecialchars is famously associated with HTML escaping, it handles the necessary logic for embedding data into JavaScript strings when used correctly. The key parameter here is not just about converting special characters like <, >, and &; it is about ensuring that double quotes within the data do not break the enclosing attribute.

Consider this implementation pattern:

$value = $rec['NAME']; // Contains: aaa"aaa
$escapedValue = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');

When you output $escapedValue inside an HTML attribute, htmlspecialchars converts internal double quotes to HTML entities (&quot;). This ensures the browser never interprets them as string terminators. The resulting HTML might look like this:

onclick="var a = prompt('New value: ', 'aaa&quot;aaa'); if (a != null) ..."

This breaks the "ruins the code" scenario because the browser treats &quot; as a literal character sequence, not a string delimiter. Unlike addslashes(), which just adds backslashes, htmlspecialchars provides structural safety by replacing characters that have semantic meaning in the target context.

If you are strictly generating JSON objects to be parsed later rather than executing inline scripts, stick with json_encode() as it is highly optimized for this specific task. However, for direct attribute injection where you need to preserve the HTML structure while embedding data, htmlspecialchars with ENT_QUOTES is the standard. Always ensure your output encoding matches your input; specifying 'UTF-8' in the third argument of htmlspecialchars prevents encoding issues that could manifest as strange character rendering in browsers like Firefox.

Relying on database escaping functions like mysql_real_escape_string for HTML or JS output is a critical security and logic error. These functions are designed to prevent SQL injection by neutralizing quotes relative to an SQL parser, not an HTML/JS parser. Using them outside of prepared statements can lead to the exact breaking behavior you experienced. Stick to context-specific escaping: htmlspecialchars for HTML attributes and json_encode for JSON payloads.

Our network