Escaping Special Characters in Javascript

Escaping Special Characters in Javascript

To add special characters (quotes, apostrophes, etc) to a text string in JavaScript , we have to use a backslash  sign.

The following JavaScript code will throw an "Object Expected" error:

//

var msg = "I am a "good" boy." ;

alert(msg);

//

The problem is JavaScript, a string is started and stopped with a double quotes. 

To solve, we could rewrite the above script , by placing the backslash ("\") before each special character. This makes the entire string as a literal.

To solve this problem, you must place a backslash (\) before each double quote in " good ". This turns each double quote into a string literal:

//

var msg = "I am a  \"good\" boy." ;

alert(msg);

//

 

By [)ia6l0 iii   Popularity  (1899 Views)