re: Regex Cheat Sheet VIEW POST

FULL DISCUSSION
 

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);

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;

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

 

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

 
code of conduct - report abuse