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
Angular:Onclick on HTML Element According to Its Class
Parsing Error: Unexpected Token, Expected ","
What Is the Opposite of Evt.Preventdefault();
Deselect All Options in Multiple Select With 1 Option
Copy/Paste from Excel to a Web Page
How to Detect Chinese Character With Punctuation in Regex
How to Hide and Show Div by Id Based on the Value of Selected Drop Down -Jquery and JavaScript
Callback Function Cannot Access Variable Within Parent Function'S Scope
Get Start Date and End Date of Current Week (Week Start from Monday and End With Sunday )
How to Import a Script into .Vue File
How to Implement Multiple Checkbox Using React Hook
How to Put a Variable in an Src Attribute
How to Know If Browser Tab Is Already Open Using JavaScript
Javascript/Dom: How to Remove All Event Listeners of a Dom Object
How to Validate for Only CSV File Uploads Using the Pattern Attribute Using Html5
Update Url With Value from Input on Click With React
Cors - Response to Preflight Request Doesn't Pass Access Control Check