JavaScript- Special Characters.

Posted on 25/09/2009 by


Using JavaScript you can add special characters to a text String by backslash sign (\). It is used to put in apostrophes, new lines, quotes, and other special characters into a string.


Insert special characters

var txt=”This is the so-called ” magic carpet.”;

In JavaScript, a string can be started and stopped with either a single or double quotes. This means that the string above will be cut into: This is the so-called.
To solve the problem you must place a backslash (\) before each double quote in “Magic Carpet”. This turns each double quote into a string literal:


var txt=”This is the so-called \”Margic\” Carpet “;

JavaScript will now do the output  of the proper text string: This is the so-called “Magic” Carpet.

Here is another Example:

document.write (“You \& I are talking!”);

The example above will produce the following output:

You & I are talking!

The table below lists other special characters that can be added to a text string with the backslash sign.

Code Outputs
\’ single quote
\” double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

Posted in: JavaScript