This article will explain how to use escape characters to escape quotes in strings in the JavaScript programming language, with some examples.
What is a String Variable in JavaScript?
A string is a type of variable. It represents a series of zero or more characters. Other variable types are numeric, boolean, and array variables.
A variable’s type defines what values it can hold and what can be done with it. For example, string variables can be split and joined to form new strings, and numeric variables can have mathematical operations performed on them.
Usage of Quotes to Define Strings
In JavaScript, strings are defined by wrapping a series of characters in quotes and assigning that value to a variable.
JavaScript strings can contain any characters supported in the character set used by the UTF-16 character set.
var myString = "this is a string!";
Single Line Strings
Single line strings can be defined using single or double quotes:
var myString = 'this is a string!'; var myOtherString = "this is a string too!";
Multi Line Strings
Strings spanning multiple lines can be defined using backticks instead of quotes:
var myString = `this is a string spanning several lines!`;
What are Escape Characters?
That’s all pretty simple, but there’s a problem – what if you want your string to contain the same quote character which was used to define the string?
var myString = "Some guy once said "To be or not to be", or something to that effect.";
The above code will produce a syntax error, as the quotes we wish to be included in the string are interrupting the correct usage of double quotes used to define the string.
Escape characters are the solution to this – we can tell JavaScript that the double quotes in the string are part of the string itself, and that it should not treat them as the beginning or end of the string definition.
In JavaScript, the escape character for quotes used in strings is the \ (backslash) character.
Escaping Quotes
So, to prevent the quotes within the string from interfering with the JavaScript syntax for defining the string, simply place a backslash before them like so:
var myString = "Some guy once said \"To be or not to be\", or something to that effect."; console.log(myString);
The above example will output the following to the console:
Some guy once said "To be or not to be", or something to that effect.
Escaping Escape Characters
Of course, you’ll probably also want to use a \ (backslash) character in your strings at some point too. Never fear, you can also escape the escape character:
var myString = "\\"; console.log(myString);
The above code will output the following to the console:
\