JavaScript Regular Expressions (regex or regexp) are powerful tools for matching patterns in strings. They are used for validating, searching, extracting, and replacing text.
Basic Syntax
- Regex is defined in two ways:
- Literal notation:javascriptCopy code
const regex = /pattern/flags;
2. RegExp constructor:
const regex = new RegExp("pattern", "flags");
Flags
Flags modify the behavior of the regex:
- g: Global search (find all matches).
- i: Case-insensitive search.
- m: Multiline search.
- s: Dot (
.) matches newline characters. - u: Unicode support.
- y: Sticky mode (matches only from the last index).
JavaScript Regular Expressions (regex or regexp) are powerful tools for matching patterns in strings. They are used for validating, searching, extracting, and replacing text.
Basic Syntax
- Regex is defined in two ways:
- Literal notation:javascriptCopy code
const regex = /pattern/flags; - RegExp constructor:javascriptCopy code
const regex = new RegExp("pattern", "flags");
- Literal notation:javascriptCopy code
Flags
Flags modify the behavior of the regex:
- g: Global search (find all matches).
- i: Case-insensitive search.
- m: Multiline search.
- s: Dot (
.) matches newline characters. - u: Unicode support.
- y: Sticky mode (matches only from the last index).
Special Characters
- Character Classes:
.: Matches any character except newline.\w: Matches any word character (letters, digits, underscore).\W: Matches any non-word character.\d: Matches any digit (0-9).\D: Matches any non-digit.\s: Matches any whitespace (spaces, tabs).\S: Matches any non-whitespace.
- Anchors:
^: Matches the start of a string.$: Matches the end of a string.
- Quantifiers:
*: Matches 0 or more times.+: Matches 1 or more times.?: Matches 0 or 1 time.{n}: Matches exactlyntimes.{n,}: Matchesnor more times.{n,m}: Matches betweennandmtimes.
- Grouping and Alternation:
(abc): Matches “abc” as a group.|: Logical OR (alternation).javascriptCopy code
/cat|dog/.test("dog"); // true
5. Escaping:
/\./.test("a.b"); // true
Common Methods
test(): Checks if a pattern exists in a string.
const regex = /hello/i;
console.log(regex.test("Hello world")); // true
2. exec(): Returns the first match (or null).
const regex = /\d+/;
console.log(regex.exec("123abc")); // ['123']
3. match(): Finds matches (use g for all matches).
const str = "cat bat rat";
console.log(str.match(/\b\w{3}\b/g)); // ['cat', 'bat', 'rat']
4. replace(): Replaces matched substrings.
const str = "hello world";
console.log(str.replace(/world/, "there")); // "hello there"
5. search(): Finds the index of the first match.
const str = "hello world";
console.log(str.search(/world/)); // 6
6. split(): Splits a string based on a regex pattern.
const str = "a,b,c";
console.log(str.split(/,/)); // ['a', 'b', 'c']


Leave a Reply