Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Regular Expressions in JavaScript Validating a Form Validating a Phone Number

Is escape character "\" indicate a grouping? Thank you

Is escape character "\" indicate a grouping? Thank you

1 Answer

Hi 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!

Hi Peter,

Thank you for the explanation, very informative. I understand the use of '\' now. Thanks