DEV Community

Discussion on: Regex Cheat Sheet

Collapse
 
lexlohr profile image
Alex Lohr

Using the | operator is a dangerous habit. You easily forget to guard yourself against matching substrings, for example consider the following line:

const isLocalHost = /127.0.0.1|localhost/.test(location.host);
Enter fullscreen mode Exit fullscreen mode

And now what happens on localhost.mydevious.url? The secure solution is to use ^ and $ to gate the start and end of the tested string.

Also, one trick up JS regex's sleeve is the back reference (\1-\9):

/(["'])(.*?)\1/.test('"I can match Emma\'s full strings"') && RegExp.$2;
/(["'])(.*?)\1/.test("'I can match when Emma say \"things in strings\"'") && RegExp.$2;
Enter fullscreen mode Exit fullscreen mode

This will re-use the (matches) inside the same regex.

Collapse
 
c24w profile image
Chris Watson

The real guard is to write tests to assert the correct behaviour :)

Collapse
 
lexlohr profile image
Alex Lohr

Just don't forget about those edge cases ;-)