Welcome to TheCodingCollege.com! Are you looking to master pattern matching and text processing in JavaScript? Regular Expressions (regex or regexp) are the ultimate tool for searching, matching, and manipulating strings. They are powerful, versatile, and widely used in programming for tasks like form validation, data extraction, and string replacements.
In this guide, we’ll cover everything you need to know about regular expressions in JavaScript, from basic syntax to advanced use cases.
What Are Regular Expressions?
A Regular Expression is a sequence of characters that defines a search pattern. In JavaScript, regex is implemented through the RegExp object or used with string methods like .match()
, .replace()
, .search()
, and .split()
.
Syntax
Regular expressions are written between forward slashes (/pattern/
) or using the RegExp
constructor.
// Literal Syntax
const regex = /pattern/;
// Constructor Syntax
const regex = new RegExp('pattern');
Regular Expression Modifiers
Modifiers are optional flags that change the behavior of a regex pattern.
Modifier | Description | Example |
---|---|---|
g | Global search (find all matches). | /pattern/g |
i | Case-insensitive search. | /pattern/i |
m | Multi-line search. | /pattern/m |
s | Allows . to match newline characters. | /pattern/s |
u | Enables Unicode matching. | /pattern/u |
y | Sticky search (matches at exact position). | /pattern/y |
Commonly Used Regex Patterns
Character Classes
Syntax | Description |
---|---|
. | Matches any character except newline. |
\d | Matches any digit (0–9). |
\D | Matches any non-digit. |
\w | Matches any word character (a–z, A–Z, 0–9, _). |
\W | Matches any non-word character. |
\s | Matches any whitespace character. |
\S | Matches any non-whitespace character. |
Quantifiers
Syntax | Description |
---|---|
* | Matches 0 or more occurrences. |
+ | Matches 1 or more occurrences. |
? | Matches 0 or 1 occurrence. |
{n} | Matches exactly n occurrences. |
{n,} | Matches n or more occurrences. |
{n,m} | Matches between n and m occurrences. |
Anchors
Syntax | Description |
---|---|
^ | Matches the start of a string. |
$ | Matches the end of a string. |
\b | Matches a word boundary. |
\B | Matches a non-word boundary. |
Using Regular Expressions in JavaScript
1. Testing a Pattern with .test()
The .test()
method checks if a pattern exists in a string.
const regex = /hello/i;
console.log(regex.test('Hello, world!')); // Output: true
2. Searching with .exec()
The .exec()
method returns the first match as an array or null
if no match is found.
const regex = /world/;
const result = regex.exec('Hello, world!');
console.log(result);
// Output: ['world']
3. String Methods with Regex
.match()
Finds matches in a string and returns them as an array.
const text = 'The quick brown fox jumps over the lazy dog.';
const matches = text.match(/\b\w{4}\b/g);
console.log(matches); // Output: ['quick', 'brown', 'over', 'lazy']
.replace()
Replaces matched patterns with a specified replacement.
const text = 'I love JavaScript.';
const result = text.replace(/JavaScript/, 'coding');
console.log(result); // Output: I love coding.
.search()
Finds the index of the first match in a string.
const text = 'Learn regex with JavaScript.';
const index = text.search(/regex/);
console.log(index); // Output: 6
.split()
Splits a string into an array based on a regex pattern.
const text = 'apple,banana,orange';
const result = text.split(/,/);
console.log(result); // Output: ['apple', 'banana', 'orange']
Practical Use Cases of Regular Expressions
1. Form Validation
Validate email addresses, phone numbers, or passwords.
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
console.log(validateEmail('[email protected]')); // Output: true
console.log(validateEmail('invalid-email')); // Output: false
2. Search and Highlight Text
function highlight(text, keyword) {
const regex = new RegExp(`(${keyword})`, 'gi');
return text.replace(regex, '<mark>$1</mark>');
}
console.log(highlight('Learn regex at TheCodingCollege.com', 'regex'));
// Output: Learn <mark>regex</mark> at TheCodingCollege.com
3. Extract Data from Strings
const log = 'User: John, Age: 25, Location: New York';
const regex = /User:\s(\w+),\sAge:\s(\d+),\sLocation:\s([\w\s]+)/;
const [, user, age, location] = regex.exec(log);
console.log(user); // Output: John
console.log(age); // Output: 25
console.log(location); // Output: New York
4. Password Strength Checker
function checkPasswordStrength(password) {
const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return strongRegex.test(password);
}
console.log(checkPasswordStrength('StrongP@ss1')); // Output: true
console.log(checkPasswordStrength('weakpass')); // Output: false
Tips for Working with Regular Expressions
- Test Your Patterns: Use online tools like regex101 to experiment with regex patterns.
- Use Modifiers: Modifiers like
g
andi
can save you from writing extra code for common operations. - Keep Patterns Readable: Use comments or break down complex patterns for maintainability.
Why Learn Regular Expressions at TheCodingCollege.com?
At TheCodingCollege.com, we provide:
- Detailed Explanations: Learn regex concepts step by step.
- Real-World Examples: Apply regex to solve practical problems.
- Expert Guidance: Trusted resources to help you become a better coder.
Conclusion
Mastering regular expressions in JavaScript can dramatically improve your ability to manipulate strings, validate input, and parse data. While regex may seem complex at first, practice and exposure will make it an indispensable tool in your coding arsenal.