JavaScript - What is RegExp Object?
Last Updated :
05 Dec, 2024
The RegExp object in JavaScript is a powerful tool for pattern matching, searching, and manipulating strings. It allows you to define patterns for matching text and helps in validation, extraction, and replacement.
1. String Searching
Check if a String Contains a Word
JavaScript
let s = "Welcome to JavaScript!";
let regex = /JavaScript/;
console.log(regex.test(s));
Case-Insensitive Search
JavaScript
let s = "Learning javascript is fun!";
let regex = /JavaScript/i;
console.log(regex.test(s));
2. String Validation
Validate an Email Address
JavaScript
let mail = "[email protected]";
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(regex.test(mail));
Validate a Password
JavaScript
let pass = "P@ssw0rd";
let regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(regex.test(pass));
3. Pattern Matching and Extraction
Extract Phone Numbers
JavaScript
let s = "Call me at 123-456-7890 or 987-654-3210.";
let regex = /\d{3}-\d{3}-\d{4}/g;
console.log(s.match(regex));
Output[ '123-456-7890', '987-654-3210' ]
Extract Domain Names from Emails
JavaScript
let mails = "[email protected], [email protected]";
let regex = /@(\w+\.\w+)/g;
let a = [];
let match;
while ((match = regex.exec(mails)) !== null) {
a.push(match[1]);
}
console.log(a);
Output[ 'example.com', 'test.org' ]
4. Search and Replace
Replace All Occurrences of a Word
JavaScript
let s1 = "JavaScript is fun. JavaScript is powerful.";
let s2 = s1.replace(/JavaScript/g, "JS");
console.log(s2);
OutputJS is fun. JS is powerful.
Sanitize Input by Removing Special Characters
JavaScript
let s1 = "Hello@World#2024!";
let s2 = s1.replace(/[!@#]/g, "");
console.log(s2);
5. Dynamic Pattern Matching
Highlight User Input in Text
JavaScript
let s1 = "JavaScript is awesome!";
let s2 = "javascript";
let regex = new RegExp(s2, "i");
console.log(s1.replace(regex, "**JavaScript**"));
Output**JavaScript** is awesome!
Built-In Methods of RegExp
- test(): Checks if a pattern exists in a string.
- exec(): Executes a search for a match and returns details about the match.
- match(): Used with strings to find matches.
- replace(): Replaces matched text with new content.
Real-World Use Cases
- Form Validation: Ensure user inputs match required formats, like emails, phone numbers, or passwords.
- Log Parsing: Extract data like IP addresses, error messages, or timestamps from server logs.
- Dynamic Search and Highlighting: Enable search functionality with user-defined patterns, like search filters in applications.
- Data Cleaning: Remove unwanted characters or transform text into standardized formats.
- Web Scraping: Extract meaningful data from raw HTML or web content for analysis.
Similar Reads
JavaScript RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false.JavaScriptconst pattern = /hello/; const text = "hello world"; console.log(pattern.test(text));Outputtrue SyntaxRegExpObject.test(str)Where str is the stri
1 min read
JavaScript RegExp Flags Property RegExp flags are a set of optional characters added to the regular expression pattern to control its behavior. Flags modify how the pattern is interpreted during the search. They can be added after the closing / of the regular expression pattern.JavaScriptlet s = "Hello World\nhello world"; // Globa
3 min read
JavaScript - What is the Role of Global RegExp? In JavaScript, global regular expressions (RegExp objects with the g flag) are used to perform operations across the entire input string rather than stopping after the first match.To understand how the g flag works, hereâs a simple exampleJavaScriptlet s = "apple banana cherry"; // Match one or more
3 min read
JavaScript RegExp g Modifier The g (global) modifier in JavaScript regular expressions is used to perform a global search. It ensures the pattern is matched multiple times throughout the entire string, rather than stopping at the first match.JavaScriptlet regex = /cat/g; let str = "cat, caterpillar, catch a cat"; let matches =
3 min read
JavaScript RegExp exec() Method The RegExp.exec() method in JavaScript allows you to search for a pattern in a string and retrieve detailed information about the match. Unlike simple methods like test(), exec() returns not just a boolean, but an array containing the entire match, capturing groups, the position of the match, and mo
2 min read