JavaScript Tutorial – String

String is like a container for text.

JavaScript String

String can store any combination of text. You can use single or double quotes.

How to declare string in JavaScript

<script type="text/javascript">
   var website = "WhatAboutHTML";
   var website = 'WhatAboutHTML';

You can also use single or double quotes in a string, as long as they don’t match the quotes surrounding the string.

How to add quotes in String

<script type="text/javascript">
   var text1 = "It's funny";
   var text2 = "My name is 'Jay'";
Try it yourself »

Escape Special Character

The backslash escape character turns special characters into string characters.

How to escape special character in JavaScript String.

<script type="text/javascript">
   var text1 = 'It\'s funny';
   var text2 = "My name is \"Jay\"";
Try it yourself »

When you place \ in font of a character, you are telling JavaScript that the character after the backslash is to be escaped as a normal character.

List of common special characters that need to be escaped:

Code Outputs
\’ single quote
\” double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed