Since we would be looking at some string character literals, let's declare two variables holding string values to understand how the character literals are working.
/* Declare variables holding some strings */ let intro = "My name is John Doe"; let fathersName = "My father's name is Mark Doe";
Let's assume that I want to quote the name of John Doe into double-quotes for some reason. Before we do that, let me add prettier ignore so that prettier does not auto-format my code. Let's try adding double quotes now. You see, the moment
I add double quotes to John Doe, my IDE starts shouting at me because this is a syntax error. If you look closely, you will understand why so. Now the first double quote starts before
My and ends after
is. The second pair of double
Let me print the result to the console to see what we get. We have indeed added double quotes the way we wanted to.
/* Declare variables holding some strings */ let intro = "My name is \"John Doe\""; console.log ( intro ) // Output -> My name is "John Doe"
My and ending before
s over here, and then another
one starts after the word
single quote we have before
Certainly, it does work.
// prettier-ignore let fathersName = 'My father\'s name is Mark Doe'; console.log ( fathersName ); // Output -> My father's name is Mark Doe
Okay, let's have a look at another one here. For this, let me copy our intro variable, create another variable, and name it intro2 and remove these double-quotes. Cool! Now, let us assume that I want to add a backslash at the end of John
Doe's name for some reason. Let's add a backslash and print it to the console to see what we get.
let intro2 = 'My name is John Doe \ '; console.log ( intro2 )
backslash. So we would need to add another backslash after the first one. Now you see we get the desired result.
let intro2 = 'My name is John Doe \\ '; console.log ( intro2 )
Let's assume that we wanted to print these two sentences together but in two different lines. I will create another variable so that you have the previous one available for your records. I will try to concatenate them and see what we get.
You see, we did join the two sentences, but we don't get them in two separate lines. For that, we can use a new line character literal. Let's add the escape character followed by
\n. This creates a new line. A syntax of declaring string
let intro3 = 'My name is John Doe \n'; console.log ( intro3 + fathersName ); // \n - for adding a new line
/* * \b Backspace * \f Form Feed * \n New Line * \r Carriage Return * \t Horizontal Tabulator * \v Vertical Tabulator * */
I hope this article was helpful.
suggestions, please feel free to