Original link: https://www.sey.ink/5458/
Defining a string must enclose it in single or double quotes. So what do you do when your string contains quotes "
or '
?
In JavaScript, quotes can be escaped by preceding them with a backslash ( \
).
const sampleStr = "Alan said, \"Peter is learning JavaScript\".";
With the escape symbol, JavaScript knows that this single or double quote is not the end of the string, but a character within the string. So, the result of the above string printed to the console is:
Alan said, "Peter is learning JavaScript".
Strings in JavaScript can be represented by single or double quotes that start and end with the same type. Unlike some other programming languages, the function of single and double quotes is the same in JavaScript.
const doubleQuoteStr = "This is a string"; const singleQuoteStr = 'This is also a string';
When you need to use multiple quotes in a string, you can use single quotes to wrap double quotes or vice versa. Common scenarios such as sentences containing dialogue in a string need to be enclosed in quotes. In addition, for example, in a string containing an <a>
tag, the attribute value of the tag needs to be enclosed in quotation marks.
const conversation = 'Finn exclaims to Jake, "Algebraic!"';
However, this becomes a problem if you need to use outer quotes in it. Remember, a string has the same quotes at the beginning and end. Be aware that strings have the same quotes at the beginning and end, and if the same quotes are used in the middle, the string will abort early and throw an error.
const goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"'; const badStr = 'Finn responds, "Let's go!"';
Here badStr
will generate an error.
In goodStr above, both kinds of quotes can be safely used by using the backslash \
escape character.
Tip: Don’t confuse backslash \
and slash /
. They are not the same thing.
The post Quotes in JavaScript Escape Strings appeared first on Senson Blog .
This article is reprinted from: https://www.sey.ink/5458/
This site is for inclusion only, and the copyright belongs to the original author.