Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHanwen Zhang
20,084 PointsIs escape character "\" indicate a grouping? Thank you
Is escape character "\" indicate a grouping? Thank you
1 Answer
Peter Vann
36,427 PointsHi Hanwen!
When you escape a character in RegEx (put \ before it), then that character is interpreted as that character literally and not as some other RegEx-related symbol.
This is not RegEx related, but illustrates how escape characters work.
Consider this code:
const str = 'This is my sister's coat'; // Note: s coat is NOT part of the string
It will error, because the apostrophe in sister's will be interpreted as the end of the string.
(Because there are actually 3 single quotes.)
One way to easily fix the issue is with an escape character.
If you instead type it this way:
const str = 'This is my sister\'s coat';
JS will interpret the middle single quote as literally a single quote character and NOT the end of the string.
(In fact, the MarkDown color coding really shows the difference, if you noticed it.)
The \ plays the same role in RegEx.
Does that make sense?
More info:
https://www.regular-expressions.info/characters.html
https://javascript.info/regexp-escaping
I hope that helps.
Stay safe and happy coding!
Hanwen Zhang
20,084 PointsHanwen Zhang
20,084 PointsHi Peter,
Thank you for the explanation, very informative. I understand the use of '\' now. Thanks