Method 1: Using backsplash character
const message1 = 'I\'m sorry. That\'s all my fault'; const message2 = '\"Flashlight\" is my favourite song'; console.log(message1) console.log(message2)
I'm sorry. That's all my fault "Flashlight" is my favourite song
As you can see, putting a backslash before every single quote or double quote helps us to escape the quotes in the string.
Method 2: Using the backticks
Another method I want to mention that helps you escape quotes in strings is to use the backticks (`) character.
Using backticks as the outermost bracket makes it possible to use both single and double quotes in strings normally.
Take a look at this example:
const message = `That's music is from the movie "Harry Potter"` console.log(message )
That's music is from the movie "Harry Potter"
As a result, your string is surrounded by the backticks (`), so you are free to use single and double quotes in the string without having to escape them.
Method 3: Changing the outer quotes
There is still one more simple way to help escape quotes in a string. We use alternating single and double quotes. That means when we use single quotes as outer quotes of the string, we can use double quotes as string characters and vice versa.
const message1 = 'She greeted me: "Have a nice day, Steve"' const message2 = "It's right there" console.log(message1) console.log(message2)
She greeted me: "Have a nice day, Steve" It's right there
The results displayed on the console window are still as we expected. This method can be considered the most straightforward way for you to escape the quotes in a string.
Maybe you are interested:
Name of the university: HUST