Escaping Special Characters in Javascript

By [)ia6l0 iii

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);

//

 

Popularity  (1433 Views)
Picture
Biography - [)ia6l0 iii
When things go wrong don't get blue, Just smile and say I'll get thru !!!
Create New Account
Article Discussion: Escaping Special Characters in Javascript
[)ia6l0 iii posted at Friday, October 24, 2008 12:11 PM
reply