Apostrophe code in JS


#1

Why is backslash \ used before the apostrophe ‘ code?

Example:
To code the word I’m, I\2019m is used as its code.


#2

Since a string uses quotes to mark the beginning and end, there needs to be a way to show the difference between an apostrophe and the end of the string. JavaScript allows single quotes or double quotes for a string, so a simple way to avoid the confusion is to use the other type than the contents of your string. In the app, it always uses single quotes, so we can’t do this.

The backslash is called an escape character. This tells the string that it’s not finished yet, but the next character should be treated carefully.

'It wasn't me' - bad, the apostrophe isn’t escaped, so the string turns into 'It wasn'and then the code after will try to be interpreted as a string
"It wasn't me" - good, the string is surrounded with double quotes, so the apostrophe is fine
'It wasn\'t me' - good, the apostrophe is “escaped” so the string will interpret it as just the ' character and not the end of the string

If there is a special character are in a string, it may be escaped with a backslash and then the character is represented with its unicode code point. U+2019 is the “right single quotation mark”. You can see other examples of this by trying to put an emoji in a string.

–Frankie


#3

Thank you for the examples @Grasshopper_Frankie !