JavaScript RegExp Methods
Essential methods for pattern matching and text manipulation
⚙️ What are RegExp Methods?
RegExp methods are built-in functions that allow you to test patterns, find matches, and manipulate text. These methods are available on RegExp objects and some String methods also work with regular expressions.
// Basic method example
let regex = /hello/i;
let text = "Hello World";
console.log(regex.test(text)); // true
console.log(regex.exec(text)); // ["Hello", index: 0, ...]
Output:
["Hello", index: 0, input: "Hello World", groups: undefined]
Core RegExp Methods
test()
Tests if pattern matches
regex.test(string)
exec()
Executes search for match
regex.exec(string)
toString()
Returns string representation
regex.toString()
compile()
Deprecated method
// Don't use
🔹 test() Method
The test() method returns true if the pattern matches:
// Using test() method
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
let emails = [
"[email protected]",
"invalid-email",
"[email protected]",
"not.an.email"
];
console.log("Email validation results:");
emails.forEach(email => {
let isValid = emailRegex.test(email);
console.log(`${email}: ${isValid ? 'Valid' : 'Invalid'}`);
});
// Case-insensitive test
let caseRegex = /hello/i;
console.log("\nCase-insensitive test:");
console.log("HELLO:", caseRegex.test("HELLO"));
console.log("hello:", caseRegex.test("hello"));
console.log("Hi there:", caseRegex.test("Hi there"));
Output:
[email protected]: Valid
invalid-email: Invalid
[email protected]: Valid
not.an.email: Invalid
Case-insensitive test:
HELLO: true
hello: true
Hi there: false
🔹 exec() Method
The exec() method returns detailed match information:
// Using exec() method
let regex = /(\w+)\s+(\d+)/g;
let text = "apple 5 banana 3 orange 7";
console.log("Finding word-number pairs:");
let match;
while ((match = regex.exec(text)) !== null) {
console.log(`Full match: "${match[0]}"`);
console.log(`Word: "${match[1]}"`);
console.log(`Number: "${match[2]}"`);
console.log(`Index: ${match.index}`);
console.log(`---`);
}
// Single exec() call
let phoneRegex = /(\d{3})-(\d{3})-(\d{4})/;
let phoneText = "Call me at 123-456-7890";
let phoneMatch = phoneRegex.exec(phoneText);
if (phoneMatch) {
console.log("Phone number found:");
console.log("Full number:", phoneMatch[0]);
console.log("Area code:", phoneMatch[1]);
console.log("Exchange:", phoneMatch[2]);
console.log("Number:", phoneMatch[3]);
}
Output:
Full match: "apple 5"
Word: "apple"
Number: "5"
Index: 0
---
Full match: "banana 3"
Word: "banana"
Number: "3"
Index: 8
---
Phone number found:
Full number: 123-456-7890
Area code: 123
Exchange: 456
Number: 7890
🔹 String Methods with RegExp
String methods that work with regular expressions:
// String methods with RegExp
let text = "The quick brown fox jumps over the lazy dog";
let regex = /\b\w{4}\b/g; // 4-letter words
// match() - find all matches
let matches = text.match(regex);
console.log("4-letter words:", matches);
// search() - find first match index
let searchIndex = text.search(/fox/);
console.log("'fox' found at index:", searchIndex);
// replace() - replace matches
let replaced = text.replace(/\b\w{3}\b/g, "***");
console.log("3-letter words replaced:", replaced);
// split() - split by pattern
let words = text.split(/\s+/);
console.log("Word count:", words.length);
console.log("First 3 words:", words.slice(0, 3));
Output:
'fox' found at index: 16
3-letter words replaced: *** quick brown *** jumps over *** lazy ***
Word count: 9
First 3 words: ["The", "quick", "brown"]
🔹 Advanced Method Usage
Combining methods for complex text processing:
// Text processing with multiple methods
function analyzeText(text) {
let results = {
wordCount: 0,
sentences: 0,
emails: [],
phoneNumbers: [],
urls: []
};
// Count words
let wordRegex = /\b\w+\b/g;
let wordMatches = text.match(wordRegex);
results.wordCount = wordMatches ? wordMatches.length : 0;
// Count sentences
let sentenceRegex = /[.!?]+/g;
let sentenceMatches = text.match(sentenceRegex);
results.sentences = sentenceMatches ? sentenceMatches.length : 0;
// Find emails
let emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
results.emails = text.match(emailRegex) || [];
// Find phone numbers
let phoneRegex = /\b\d{3}-\d{3}-\d{4}\b/g;
results.phoneNumbers = text.match(phoneRegex) || [];
// Find URLs
let urlRegex = /https?:\/\/[^\s]+/g;
results.urls = text.match(urlRegex) || [];
return results;
}
let sampleText = `
Contact us at [email protected] or call 123-456-7890.
Visit our website at https://example.com for more information!
You can also reach support at [email protected].
`;
let analysis = analyzeText(sampleText);
console.log("Text Analysis Results:");
console.log("Words:", analysis.wordCount);
console.log("Sentences:", analysis.sentences);
console.log("Emails:", analysis.emails);
console.log("Phone numbers:", analysis.phoneNumbers);
console.log("URLs:", analysis.urls);
Output:
Words: 20
Sentences: 3
Emails: ["[email protected]", "[email protected]"]
Phone numbers: ["123-456-7890"]
URLs: ["https://example.com"]