Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly escape quotes inside HTML attributes?

People also ask

How do you escape quotes in HTML?

JavaScript Strings Escaping quotes Quotes in HTML strings can also be represented using ' (or ' ) as a single quote and " ( or " ) as double quotes. Note: The use of ' and " will not overwrite double quotes that browsers can automatically place on attribute quotes.

How do you escape a double quote in HTML?

The escape code " can also be used instead of " . Show activity on this post. Using " is the way to do it.

How do you escape a quote?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do you escape quotes in a string?

To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' .


" 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 &.