Before this lesson
Understand strings, Boolean conditions and functions. The dedicated regex course offers another starting point.
What you will be able to do
Design small explainable patterns and use counterexamples to distinguish matching from full validation.
Understand the mechanism
Use regex for textual patterns, not every business rule. Define characters, length and boundaries first. Availability or resource existence requires more than matching, and simple substring searches often need only includes.
Character classes describe allowed characters, quantifiers repetition and anchors position. test succeeds for a match, not automatically a full-string validation. Understand newline and multiline behavior rather than assuming anchors solve every edge case.
Global or sticky tests advance lastIndex, which can surprise repeated validation. Independent validation usually does not need those flags. Use captures for extraction and named functions with counterexamples instead of unreadable monolithic patterns.
Interpolating raw input changes pattern meaning through metacharacters. Keep patterns simple and input sizes bounded instead of using complex nested repetition on untrusted text. Server-side validation remains necessary.
Runnable example
Run the JavaScript in the Console of a separate practice page. Re-run the complete example after changing its input.
function validHandle(raw) {
// Policy: 3–16 ASCII letters, digits or underscores; first is a letter.
return raw.length >= 3 && raw.length <= 16
&& /^[A-Za-z]/.test(raw)
&& !/[^A-Za-z0-9_]/.test(raw);
}
for (const value of ['Ada_1', 'ab', '1Ada', 'Ada!', 'Ada\n', '张三']) {
console.log(JSON.stringify(value), validHandle(value));
}
const stateful = /a/g;
console.log(stateful.test('a'), stateful.test('a'));
Trace and verify
Only Ada_1 passes. Others fail length, initial-character or allowed-character rules. The final global tests yield true then false; inspect lastIndex. ASCII-only is this exercise’s explicit policy, not a universal username requirement.
Common mistakes and boundaries
Applying an ASCII handle policy to personal names is a requirements error. Prefer built-in email input semantics and appropriate server verification rather than claiming a small regex proves an address exists.
Practice challenge
Extract a positive number from lesson-42, rejecting zero, suffixes and surrounding whitespace. Return a number or null.
Reference solution and reasoning
Capture digits, verify the match covers the entire string, and check the safe-integer range before returning a number.
function lessonId(text) {
const match = /^lesson-([1-9][0-9]*)/.exec(text);
if (!match || match[0].length !== text.length) return null;
const id = Number(match[1]);
return Number.isSafeInteger(id) ? id : null;
}