Validation & small pitfalls
Validate whole strings with anchors, avoid greedy overmatch, use word boundaries, add simple extra checks, and beware /g with test().
Whole-string validation
Goal: Validate safely without surprises.
- Use ^ and $ to match the whole string
- Avoid greedy overmatch; use lazy *? when needed
- Use \\b word boundaries
- Beware /g with test()

Anchors in practice
Add ^ and $ so partial matches do not slip through.
// Validate 4–6 digits ONLY (no spaces, no letters)
function isPin(text) {
const re = /^\\d{4,6}$/;
return re.test(text);
}
console.log("1234 ->", isPin("1234"));
console.log("12 34 ->", isPin("12 34"));
console.log("a123 ->", isPin("a123"));

All lessons in this course
- Regex basics — literals, test, anchors, and flags
- Groups, Captures, and Replace
- Validation & small pitfalls