Day 9: Regular Expressions (RegEx) in JavaScript
What are Regular Expressions?
Regular Expressions, commonly known as RegEx, are patterns used to match character combinations in strings. In JavaScript, RegEx provides powerful pattern-matching capabilities that allow you to search, replace, and validate text efficiently.
Why Use RegEx?
- Validation: Validate input fields, such as email addresses, phone numbers, and passwords.
- Searching: Search for specific patterns within strings.
- Replacing: Replace occurrences of a pattern with a new substring.
- Extracting: Extract substrings that match a pattern.
How to Create a RegEx?
There are two ways to create a RegEx in JavaScript:
- Using literal notation:
const pattern = /abc/;
- Using the
RegExpconstructor:
const pattern = new RegExp('abc');
There are several methods that RegEx use such as test, exec, match, replace, split… each has its usage
#Example:
Matching Digits
const pattern = /\d+/;
console.log(pattern.test('123')); // true