JS RegExp Quantifiers
In this page:
x* // 0 or more
x+ // 1 or more
x? // 0 or 1
x{n} x{n,m}
Zero or More: *
* matches zero or more occurrences of the preceding element -- ab*c matches "ac" (zero b's), "abc" (one b), "abbbc" (many b's), and so on, since even zero repetitions still counts as a valid match.
उदाहरण: Zero or More: *
console.log(/ab*c/.test("ac")); // true, zero b's
console.log(/ab*c/.test("abbbc")); // true, many b's
One or More: +
+ requires at least one occurrence of the preceding element -- \d+ matches "5", "42", or "123456", but fails to match anywhere at all in a string with no digits, unlike * which would still technically match zero characters.
उदाहरण: One or More: +
console.log(/\d+/.test("42")); // true
console.log(/\d+/.test("abc")); // false, no digits at all
Zero or One: ?
? makes the preceding element optional -- present zero or one time, never more -- colou?r matches both "color" (without the u) and "colour" (with it), handling both American and British spellings with a single pattern.
उदाहरण: Zero or One: ?
console.log(/colou?r/.test("color")); // true
console.log(/colou?r/.test("colour")); // true
Specific Ranges with {n,m}
{n} matches exactly n occurrences, {n,} matches at least n, and {n,m} matches between n and m occurrences (inclusive) -- giving precise control over repetition count beyond the broader */+/? shorthand, useful for things like validating a fixed-length code.
उदाहरण: Specific Ranges with {n,m}
console.log(/^\d{3}$/.test("123")); // true, exactly 3
console.log(/^\d{2,4}$/.test("12345")); // false, too many
Greedy vs Lazy Matching
By default, quantifiers are greedy -- they match as much text as possible while still allowing the overall pattern to succeed.
Adding a ? right after a quantifier (like *? or +?) makes it lazy instead, matching as little text as possible, which matters when a pattern could otherwise "overshoot" across more text than intended.
उदाहरण: Greedy vs Lazy Matching
console.log("<a><b>".match(/<.*>/)[0]); // greedy: "<a><b>"
console.log("<a><b>".match(/<.*?>/)[0]); // lazy: "<a>"
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML