Escape an apostrophe under javascript

In Javascript an apostrophe is used to insert a piece of string into a code. However, if the piece of the string has special characters like an apostrophe, a quote, or a double quote, it can lead to errors while processing the code. For webmasters this error can be a major problem. Javascript provides a way of avoiding these types of syntax errors by using the backlash character effectively. The backlash character is used to escape these special characters without any problems. PHP provides addslashes as a means of escaping special characters and can also be used as an alternative to Javascript.
In Javascript, an apostrophe (single quote) in a string that is itself enclosed by apostrophes will cause an error.

To troubleshoot, you should escape the apostrophe by using the backslash character to let the Javascript interpreter know that it is an apostrophe within the string.

However, when the string is inserted dynamically, you should avoid any characters that can cause an error (apostrophe, quote or double quote, backslash).

Addslashes () in PHP is a useful feature for avoiding special characters easily. The function below is an excellent alternative for JavaScript:

function addslashes (ch) (     
ch.replace ch = (/ \ \ / g, "\ \ \ \")     
ch.replace ch = (/ \ '/ g, "\ '")     
ch.replace ch = (/ \ "/ g," \ \ \ "")     
return c.     

Published by aakai1056. Latest update on February 6, 2012 at 10:27 AM by Paul Berentzen.
This document, titled "Escape an apostrophe under javascript," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (
Javascript - split ()
Javascript - Delete a field of a form when clicking (focus)