JavaScript Regular Expressions
Regular expressions (regex) are powerful patterns used to match character combinations in strings. In JavaScript, they provide a concise and flexible way to search, extract, and manipulate text.
What are Regular Expressions?
A regular expression is a sequence of characters that forms a search pattern. You can use this pattern to search for matches in a string, replace parts of a string, or extract information from a string.
// Creating a regular expression
// Method 1: Using a regular expression literal
const regexLiteral = /pattern/;
// Method 2: Using the RegExp constructor
const regexConstructor = new RegExp('pattern');
Creating Regular Expressions
In JavaScript, you can create regular expressions in two ways:
// Regular expression literal
const regexLiteral = /hello/;
// RegExp constructor
const regexConstructor = new RegExp('hello');
// With flags (global, case-insensitive)
const regexWithFlags = /hello/gi;
const regexConstructorWithFlags = new RegExp('hello', 'gi');
Tip: Use the constructor method when you need to create a regex pattern dynamically from a string variable.
Regular Expression Flags
Flags modify how the pattern matching behaves:
Flag | Description | Example |
---|---|---|
g |
Global match - find all matches rather than stopping after the first match | /a/g |
i |
Case-insensitive match | /a/i |
m |
Multi-line match - ^ and $ match start/end of each line | /^start/m |
s |
Dot (.) matches newline characters | /a.b/s |
u |
Unicode - treat pattern as a sequence of Unicode code points | /\u{1F600}/u |
y |
Sticky - matches only from the index indicated by the lastIndex property | /a/y |
Basic Pattern Matching
Regular expressions can contain simple characters that match exactly what you're looking for:
const text = "Hello, world!";
// Test if a pattern exists in a string
const hasHello = /Hello/.test(text);
console.log(hasHello); // true
// Find the first match
const match = text.match(/world/);
console.log(match[0]); // "world"
console.log(match.index); // 7
// Find all matches
const allMatches = text.match(/l/g);
console.log(allMatches); // ["l", "l", "l"]
// Replace matches
const replaced = text.replace(/o/g, "0");
console.log(replaced); // "Hell0, w0rld!"
Special Characters and Metacharacters
Regular expressions include special characters that have specific meanings:
Character | Description | Example |
---|---|---|
. |
Matches any single character except newline | /h.t/ matches "hat", "hot", "hit", etc. |
^ |
Matches the start of a string | /^Hello/ matches "Hello world" but not "world Hello" |
$ |
Matches the end of a string | /world$/ matches "Hello world" but not "world Hello" |
* |
Matches 0 or more occurrences of the preceding character | /a*/ matches "", "a", "aa", "aaa", etc. |
+ |
Matches 1 or more occurrences of the preceding character | /a+/ matches "a", "aa", "aaa", but not "" |
? |
Matches 0 or 1 occurrence of the preceding character | /colou?r/ matches "color" and "colour" |
\ |
Escapes a special character | /\./ matches "." instead of any character |
Character Classes
Character classes allow you to match any one of a set of characters:
// Using character classes
const text = "Contact us at info@example.com or call 555-123-4567";
// Extract email address
const emailRegex = /\w+@\w+\.\w+/;
const email = text.match(emailRegex);
console.log(email[0]); // "info@example.com"
// Extract phone number
const phoneRegex = /\d{3}-\d{3}-\d{4}/;
const phone = text.match(phoneRegex);
console.log(phone[0]); // "555-123-4567"
Common Regular Expression Methods
JavaScript provides several methods for working with regular expressions:
Method | Description |
---|---|
test() |
Tests if a pattern exists in a string |
exec() |
Executes a search for a match and returns an array of information |
match() |
Returns an array of matches |
search() |
Returns the index of the first match |
replace() |
Replaces matches with a replacement string |
split() |
Splits a string into an array of substrings based on a separator pattern |
Interactive Demo
Try out this interactive example to test regular expressions:
Click "Test Regular Expression" to see results
Next Steps
Now that you understand regular expressions in JavaScript, you can explore related topics:
- Advanced regex patterns for specific use cases
- Form validation with regular expressions
- Text parsing and extraction techniques
- Regular expression performance optimization
- Regular expression testing tools