Escape an apostrophe under javascript

October 2016

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.     

Related :

This document entitled « Escape an apostrophe under javascript » from CCM ( is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.