JavaScript Regex Tutorial
JavaScript Regex Tutorial
Introduction to Regular Expressions
Regular Expressions (Regex) are patterns used to match character combinations in strings. In JavaScript, regex is implemented using the RegExp
object or regex literals.
What You Will Learn:
- Basics of regex syntax
- Creating regex in JavaScript
- Common patterns and modifiers
- Regex methods in JavaScript (
test
,exec
,match
, etc.) - Practical examples
1. What is Regex in JavaScript?
In JavaScript, a regular expression is a sequence of characters that forms a search pattern.
let pattern = /abc/;
let regex = new RegExp("abc");
When to Use?
- Input validation (e.g., email, phone number)
- Searching within strings
- Data cleaning and parsing
2. Regex Syntax and Structure
Literals and Meta-characters
abc
→ matches ‘abc’\d
→ matches any digit (same as[0-9]
)\w
→ matches any word character (letters, digits, underscore).
→ matches any character except newline^
→ matches the beginning of a string$
→ matches the end of a string
Quantifiers
*
→ 0 or more+
→ 1 or more?
→ 0 or 1{n}
→ exactly n times{n,}
→ n or more times{n,m}
→ between n and m times
Character Sets
[abc]
→ a, b, or c[^abc]
→ not a, b, or c[a-z]
→ all lowercase letters
Groups and Ranges
(abc)
→ matches ‘abc’ as a group(a|b)
→ matches either ‘a’ or ‘b’
3. Regex Modifiers (Flags)
i
→ case-insensitiveg
→ global (match all)m
→ multiline
let regex = /hello/i; // case-insensitive match
let result = regex.test("HELLO"); // true
4. Creating Regex in JavaScript
Using Literal Notation
let pattern = /hello/;
Using RegExp Constructor
let pattern = new RegExp("hello");
5. Regex Methods in JavaScript
test()
– Returns true/false
let pattern = /cat/;
console.log(pattern.test("The cat is here")); // true
exec()
– Returns the first match with details
let result = /dog/.exec("The dog barks");
console.log(result); // ["dog", index: 4, input: "The dog barks", ...]
match()
– Used with strings
let text = "one two three";
console.log(text.match(/\w+/g)); // ["one", "two", "three"]
replace()
– Replace using regex
let text = "I have 2 apples";
console.log(text.replace(/\d/, "two")); // I have two apples
search()
– Returns index of first match
console.log("hello world".search(/world/)); // 6
split()
– Splits string using regex
console.log("a,b;c".split(/[,;]/)); // ["a", "b", "c"]
6. Real-World Examples
Validate Email
let emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
console.log(emailPattern.test("user@example.com")); // true
Validate Phone Number
let phonePattern = /^\d{10}$/;
console.log(phonePattern.test("9876543210")); // true
Extract All Numbers
let str = "Price: 100, Discount: 20";
console.log(str.match(/\d+/g)); // ["100", "20"]
Remove Extra Spaces
let messy = " Hello World ";
let clean = messy.replace(/\s+/g, " ").trim();
console.log(clean); // "Hello World"
7. Tips and Best Practices
- Always test regex with tools like regex101.com
- Use capturing groups
()
only when necessary - Make use of non-capturing groups
(?:...)
when groups are not needed for references - Keep regex readable: break down complex patterns with comments if possible