JS RegExp Metachars
In this page:
. ^ $ \b \B | \
The Dot: Matching Any Character
. matches any single character except a newline by default -- c.t matches "cat", "cot", "c8t", or literally any three-character sequence starting with c and ending with t, which is powerful but can be overly broad if you actually meant a specific character.
उदाहरण: The Dot: Matching Any Character
console.log(/c.t/.test("cat")); // true
console.log(/c.t/.test("c8t")); // true, . matches any character
Anchors: ^ and $
^ anchors a match to the very start of the string (or line, with m), and $ anchors to the very end -- combining both, ^pattern$ requires the entire string to match the pattern exactly, not just contain it somewhere within.
उदाहरण: Anchors: ^ and $
console.log(/^cat$/.test("cat")); // true, exact match
console.log(/^cat$/.test("concatenate")); // false, must match entire string
Alternation with |
| means "or" within a pattern -- cat|dog matches either "cat" or "dog", and combined with grouping parentheses, gr(a|e)y matches both "gray" and "grey" by allowing either character in that one position.
उदाहरण: Alternation with |
// Print `/cat|dog/.test("I have a dog")` to the console
// Print `/cat|dog/.test("I have a dog")` to the console
console.log(/cat|dog/.test("I have a dog"));
// Print `/gr(a|e)y/.test("grey")` to the console
// Print `/gr(a|e)y/.test("grey")` to the console
console.log(/gr(a|e)y/.test("grey"));
// Print `/gr(a|e)y/.test("gray")` to the console
// Print `/gr(a|e)y/.test("gray")` to the console
console.log(/gr(a|e)y/.test("gray"));
Escaping Special Characters
Any metacharacter (. ^ $ | ? * + ( ) [ ] { } \) needs a backslash before it to be treated as a literal character rather than its special regex meaning -- essential whenever your pattern needs to match one of these symbols as actual text.
उदाहरण: Escaping Special Characters
console.log(/3\.14/.test("3.14")); // true, literal dot
console.log(/3\.14/.test("3x14")); // false
Word Boundaries with \b
\b matches a position between a word character and a non-word character (or the start/end of the string), without matching any character itself -- \bcat\b matches the standalone word cat but not cat as part of category or scatter.
उदाहरण: Word Boundaries with \b
console.log(/\bcat\b/.test("I have a cat")); // true, whole word
console.log(/\bcat\b/.test("category")); // false, part of a longer word
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