DEV Community

Discussion on: How YOU can learn enough RegEx in JavaScript to be dangerous

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

Here are a couple of conventions I use when writing Regular Expressions to avoid some hazards:
1) Top & Tail: where appropriate (whole pattern matching) prefix the pattern with ^ and suffix with $ to limit the scope.
2) Limit repetition: Using {,n} and {1,n} instead of * and + for repeated groups/characters, when an upper limit (n) can be assumed. Even if n is a really big number it is usually better than unlimited.
I have also found it is just as important to confirm negative tests as positive tests. When confirming pattern make sure it not only matches the fragments of text you expect but also does not match text that is close but invalid.
A good learning/test resource I often refer to is regexr.com.

Collapse
 
softchris profile image
Chris Noring

Thank you for sharing :)