Easy tech stuff!

Escape single quotes(‘) in JavaScript

Posted: January 14th, 2008 | Author: Nischal Shetty | Filed under: JavaScript | Tags: , , , | 3 Comments »

There may be instances where you need to display single quotes in an alert box. Or may be double quotes too. To have these displayed without any errors all you need to do is add a backslash “\” before the single quote or double quote. That’s it!!!

Example: alert(“Hi! Welcome to my \’blog\’. This can also be displayed as \”blog\”.”);

The output in the alert window will be:

Hi! Welcome to my ‘blog’. This can also be displayed as “blog” .

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png

3 Comments on “Escape single quotes(‘) in JavaScript”

  1. 1 Matt said at 5:36 pm on November 3rd, 2008:

    Can you explain how to make this work? basically I want to display an alert on the click of an element that has both single and double quotes in the text. Thanks!

    click for alert

  2. 2 Nischal Shetty said at 5:45 pm on November 3rd, 2008:

    ok, suppose the text to be displayed in the alert is – I love ‘Java’ and this is my “Blog”. You would write this as

    alert(“I love \’Java\’ and this is my \”Blog\” “);

    This is the safest way to write. Hope you get it ;)

  3. 3 Mike said at 5:58 am on March 19th, 2010:

    I have a link that calls a javascript function within a php page. I’m trying to find a way to make it work, but I think it keeps breaking at the single quote:

    Server Info

    I’ve tried heredoc as well, but that didn’t resolve the issue either.


Leave a Reply