How to Escape an Ampersand in a JavaScript String So That the Page Will Validate Strict

How do I escape an ampersand in a javascript string so that the page will validate strict?

Try putting your javascript inside a CDATA block like this:

<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>

which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't understand the CDATA tag:

<script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>

Javascript quitting on an ampersand "&"

encodeURIComponent(document.title)

Why does my site not validate?

This caused by validating against XHTML - XHTML, being XML, doesn't/can't make special CDATA amends for [script] elements.

It is valid as HTML (4 or 5) - in fact, encoding the characters as suggested will break the JavaScript in an HTML context!

This issue can be resolved by:

  • Ensuring the server sends the HTML (not XHMTL/XML) Content-Type and/or;
  • Using an HTML doctype (e.g. <!DOCTYPE HTML>) or;
  • Explicitly telling the validator to check against HTML or;
  • Writing valid XHTML, if the source is indeed XHTML

In summary: XHTML is not HTML.

Unescaping ampersand characters in javascript

You need to decode them like this:

$('#myText').val($("<div/>").html(str).text());

Demo: http://jsfiddle.net/QUbmK/

You can move the decode part to function too and call that instead:

function jDecode(str) {
return $("<div/>").html(str).text();
}

$('#myText').val(jDecode(str));


Related Topics



Leave a reply



Submit