How to Escape a Double Quote in JavaScript

How to Escape a Double Quote in JavaScript thumbnail
Escaping characters keeps them from being treated as part of the JavaScript language.

JavaScript is a client-side language that is used extensively when messaging users (with strings) regarding their input. Many characters used in JavaScript strings, such as double quotes, ampersands and apostrophes, can break JavaScript programs because the language uses these characters for specific purposes. By using escape characters, developers can use these special characters in strings, instructing the browser to interpret the characters as literal values instead of as programming constructs. The JavaScript escape character is the forward-slash (“\”).

Things You'll Need

  • Text editor
Show More

Instructions

    • 1

      Open a text editor and create a new file named "escapeChar.html." The standard process for creating new files in a text editor is to select “New” from the “File” menu.

    • 2

      Add HTML tags to escapeChar.html to create a basic Web page:

      <html>
      <head></head>
      <body></body>
      </html>

    • 3

      Add a “<script>” tag between the “<body>” and “</body>” HTML tags. Give the <script> tag a “type” attribute “text/javascript” and add a closing JavaScript “</script>” tag:

      <script type="text/javascript">
      </script>

    • 4

      Add a JavaScript “document.write” method to between the “<script type="text/javascript">” and “</script>” tags. Place the text “This is an \”escape\” character” inside two parentheses after the document.write method:

      document.write("This is an \"escape\" character");

      The forward slash escapes the double quote characters in the text string so they are not interpreted as part of the method. When complete, the code will look like the following:

      <html>
      <head></head>
      <body>
      <script type="text/javascript">
      document.write("This is an \"escape\" character");
      </script>
      </body>
      </html>

    • 5

      Open escapeChar.html in a Web browser. Verify that the text “This is an “escape” character” is written to the page and includes double quotes around the word “escape.”

Tips & Warnings

  • JavaScript strings can use using single quotes, in which case double quotes do not need to be escaped. However, single quotes would then require escape characters.

  • Escape characters can be used to style text used in JavaScript "alert" and "prompt" boxes.

  • JavaScript encode and decode functions can be used in to escape special characters in certain circumstances, such as when using URLs.

  • Escape characters may not work as expected when used with bookmarklets.

Related Searches:

References

Resources

  • Photo Credit Michael Blann/Lifesize/Getty Images

Comments

Related Ads

Featured