Regular Expressions
Regular Expressions, or regex, are patterns used to match and manipulate strings. They are useful for tasks like searching, validating, or replacing text in a string.
What is a Regular Expression?
A regular expression is a sequence of characters that defines a search pattern. Think of it as a tool that can:
- Find specific text.
- Validate formats (like emails, phone numbers).
- Replace parts of a string.
Basic Syntax
Regular expressions are written between two forward slashes (/) in JavaScript.
let regex = /pattern/; // Example of a regex
How to Use Regex in JavaScript
JavaScript provides two main ways to use regular expressions:
- With RegExp methods (test, exec).
- With string methods (match, replace, search, split).
Common Regular Expression Methods
test()
Checks if a pattern exists in a string. Returns true or false.
let regex = /hello/; console.log(regex.test("hello world")); // true console.log(regex.test("hi there")); // false
exec()
Finds and returns the first match as an object, or null if no match is found.
let regex = /world/; let result = regex.exec("hello world"); console.log(result); // ["world"] console.log(result.index); // 6 (position of the match)
match()
Used with strings to return matches of a regex.
let regex = /world/; let result = regex.exec("hello world"); console.log(result); // ["world"] console.log(result.index); // 6 (position of the match)
replace()
Replaces part of a string based on a pattern.
let str = "hello world"; let result = str.replace(/world/, "JavaScript"); console.log(result); // "hello JavaScript"
search()
Finds the position of the first match, or -1 if not found.
let str = "hello world"; console.log(str.search(/world/)); // 6 console.log(str.search(/JavaScript/)); // -1
split()
Splits a string into an array based on a pattern.
let str = "apple, banana, cherry"; let result = str.split(/, /); console.log(result); // ["apple", "banana", "cherry"]
Regex Syntax
Basic Characters
/abc/ - Matches the exact sequence "abc".
/hello/ - Matches "hello".
Special Characters
1. . (dot): Matches any single character.
let regex = /h.llo/; console.log(regex.test("hello")); // true console.log(regex.test("hxllo")); // true
2. ^: Matches the start of a string.
let regex = /^hello/; console.log(regex.test("hello world")); // true console.log(regex.test("world hello")); // false
3. $: Matches the end of a string.
let regex = /world$/; console.log(regex.test("hello world")); // true console.log(regex.test("world hello")); // false
4. *: Matches 0 or more of the preceding character.
let regex = /he*/; console.log(regex.test("h")); // true console.log(regex.test("heeeee")); // true
5. +: Matches 1 or more of the preceding character.
let regex = /he+/; console.log(regex.test("h")); // false console.log(regex.test("heeeee")); // true
6. ?: Makes the preceding character optional.
let regex = /colou?r/; console.log(regex.test("color")); // true console.log(regex.test("colour")); // true
7. |: Acts like "OR".
let regex = /cat|dog/; console.log(regex.test("I have a cat")); // true console.log(regex.test("I have a dog")); // true
Character Sets
1. [abc]: Matches any one of the characters inside the brackets.
let regex = /[aeiou]/; console.log(regex.test("hello")); // true (matches 'e') console.log(regex.test("sky")); // false
2. [^abc]: Matches any character NOT inside the brackets.
let regex = /[^aeiou]/; console.log(regex.test("sky")); // true (matches 's', 'k', or 'y')
3. [a-z]: Matches a range of characters.
let regex = /[a-z]/; console.log(regex.test("hello")); // true console.log(regex.test("1234")); // false
Quantifiers
Quantifiers specify how many times a character or group should appear:
- {n}: Exactly n times.
- {n,}: At least n times.
- {n,m}: Between n and m times.
let regex = /a{2,4}/; console.log(regex.test("aaa")); // true (matches 2-4 'a's) console.log(regex.test("a")); // false
Escape Characters
To use special characters literally, escape them with a backslash (\):
let regex = /\./; console.log(regex.test("hello.")); // true console.log(regex.test("hello")); // false
Real-World Examples
Validate an Email Address
let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; console.log(emailRegex.test("example@gmail.com")); // true console.log(emailRegex.test("not-an-email")); // false
Match a Phone Number
let phoneRegex = /^\d{10}$/; console.log(phoneRegex.test("1234567890")); // true console.log(phoneRegex.test("123-456-7890")); // false
Replace All Whitespace
let str = "Hello world!"; let result = str.replace(/\s+/g, " "); console.log(result); // "Hello world!"