JS RegExp Classes
In this page:
[abc] [^abc] [a-z]
\d \w \s
\D \W \S
Digits with \d
\d matches any single digit character, 0 through 9 -- \d\d\d matches exactly three consecutive digits, and \d+ (combined with a quantifier) matches one or more digits in a row, the basis for matching numbers, phone digits, or zip codes.
उदाहरण: Digits with \d
console.log(/\d\d\d/.test("123")); // exactly 3 digits
console.log("Phone: 12345".match(/\d+/));
Word Characters with \w
\w matches any letter (upper or lower case), digit, or underscore -- effectively the set of characters typically valid in a variable name or simple identifier -- but notably does NOT include spaces, hyphens, or most punctuation.
उदाहरण: Word Characters with \w
console.log(/^\w+$/.test("user_1")); // true, letters/digits/underscore
console.log(/^\w+$/.test("user 1")); // false, contains a space
Whitespace with \s
\s matches any whitespace character -- a regular space, a tab, or a newline -- useful for splitting text on any kind of whitespace or normalizing inconsistent spacing, rather than matching only a literal space character.
उदाहरण: Whitespace with \s
console.log("a\tb c".split(/\s/)); // splits on tab and spaces alike
Negated Classes: \D, \W, \S
The uppercase versions of the shorthand classes match the exact opposite of their lowercase counterparts -- \D matches any non-digit, \W matches any non-word-character, and \S matches any non-whitespace character.
उदाहरण: Negated Classes: \D, \W, \S
console.log(/\D/.test("abc")); // true, non-digit found
console.log(/\W/.test("a_b")); // false, only word chars/underscore
console.log(/\S/.test(" ")); // false, only whitespace
Custom Character Classes with [ ]
Square brackets define a custom character class matching any single character from the specified set -- [aeiou] matches any single vowel, and [a-z] uses a range to match any single lowercase letter, letting you build precise character sets beyond the built-in shorthand classes.
उदाहरण: Custom Character Classes with [ ]
console.log(/[aeiou]/.test("sky")); // false, no vowels
console.log(/[a-z]/.test("ABC1")); // false, no lowercase letters
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