How do I properly escape quotes inside HTML attributes?

" is the correct way, the third of your tests:

<option value="&quot;asd">test</option>

You can see this working below, or on jsFiddle.

alert($("option")[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="&quot;asd">Test</option>
</select>

Alternatively, you can delimit the attribute value with single quotes:

<option value='"asd'>test</option>

If you are using PHP, try calling htmlentities or htmlspecialchars function.


Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.


Another option is replacing double quotes with single quotes if you don't mind whatever it is. But I don't mention this one:

<option value='"asd'>test</option>

I mention this one:

<option value="'asd">test</option>

In my case I used this solution.


If you are using JavaScript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.