Saturday, April 30, 2011

JavaScript Escape Characters - XV


When working with strings, you'll notice there are some characters that always seem to break your program. These include apostrophes, ampersands, double quotes etc.
When working with these characters, you need to use what is known as an "escape character". An escape character enables you to output characters you wouldn't normally be able to, usually because the browser will interpret it differently to what you intended.
In JavaScript, the backslash (\) is an escape character.
As an example, let's say I want to display the following text: They call it an "escape" character. Let's try that without an escape character:

Without an escape character:

<script type="text/javascript">
<!--
document.write("They call it an "escape" character");
//-->
</script>
The above code won't work as intended because, as soon as the browser encounters the first double quote, it will think that the string has finished. Further, it will result in an error because it will be expecting the closing bracket.

Code with an escape character:

<script type="text/javascript">
<!--
document.write("They call it an \"escape\" character");
//-->
</script>
The resulting output:
They call it an "escape" character
The above code will display the double quotes as intended.

No comments:

Post a Comment