- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Regular Expressions: Syntax, Usage, and Examples
JavaScript regular expressions (regex) help you search, match, and manipulate text using patterns. You can use them to validate user input, extract data, or modify text dynamically.
How to Use JavaScript Regular Expressions
You create a regular expression in JavaScript using either the literal syntax or the RegExp
constructor.
Regular Expression Syntax
// Regular expression literal
let regex = /hello/;
// RegExp constructor
let regex2 = new RegExp("hello");
- Slashes (
/ /
) define a regex literal. - The
RegExp
constructor creates a dynamic pattern.
You can test a pattern against a string using .test()
or .exec()
.
let pattern = /JavaScript/;
console.log(pattern.test("I love JavaScript")); // true
console.log(pattern.test("Python is great")); // false
When to Use JavaScript Regular Expressions
- Form validation – Validate email addresses, phone numbers, or passwords.
- Text search and replacement – Find specific words and modify them.
- Data extraction – Extract dates, numbers, or patterns from text.
Examples of JavaScript Regular Expressions
Validating an Email
let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailPattern.test("user@example.com")); // true
console.log(emailPattern.test("invalid-email")); // false
Replacing Words in a String
let text = "I love JavaScript!";
let updatedText = text.replace(/JavaScript/, "Python");
console.log(updatedText); // "I love Python!"
Extracting Numbers
let sentence = "The price is $45.99";
let price = sentence.match(/\d+\.\d+/);
console.log(price[0]); // "45.99"
Learn More About JavaScript Regular Expressions
Understanding Regular Expressions in JavaScript
Regular expressions use special characters to define patterns.
let regex = /\d{3}-\d{2}-\d{4}/; // Matches a format like 123-45-6789
console.log(regex.test("123-45-6789")); // true
console.log(regex.test("12-3456-789")); // false
\d
matches any digit (0-9).{3}
means exactly three occurrences.- `` is a literal hyphen.
Flags in Regular Expressions
Flags modify how a regex works.
let sentence = "Hello hello";
let caseInsensitivePattern = /hello/i; // Case insensitive flag (i)
console.log(caseInsensitivePattern.test(sentence)); // true
let globalPattern = /l/g; // Global search flag (g)
console.log(sentence.match(globalPattern)); // ['l', 'l', 'l', 'l']
How to Combine Two Regular Expressions in JavaScript
You can combine patterns using the pipe |
(OR operator).
let fruitPattern = /apple|banana/;
console.log(fruitPattern.test("I like bananas")); // true
console.log(fruitPattern.test("I like grapes")); // false
Advanced Regular Expressions in JavaScript
You can use lookaheads, lookbehinds, and capturing groups for advanced pattern matching.
Positive Lookahead
Matches only if another pattern follows.
let lookaheadPattern = /\d+(?= dollars)/;
console.log("20 dollars".match(lookaheadPattern)); // ["20"]
console.log("20 euros".match(lookaheadPattern)); // null
Negative Lookahead
Matches only if another pattern does not follow.
let negativeLookahead = /\d+(?! euros)/;
console.log("30 dollars".match(negativeLookahead)); // ["30"]
console.log("30 euros".match(negativeLookahead)); // null
Capturing Groups
Extracts parts of a match.
let datePattern = /(\d{4})-(\d{2})-(\d{2})/;
let result = "2024-02-01".match(datePattern);
console.log(result[1]); // "2024"
console.log(result[2]); // "02"
console.log(result[3]); // "01"
Testing Regular Expressions in JavaScript
You can use .test()
, .match()
, or .exec()
.
let pattern = /hello/;
console.log(pattern.test("hello world")); // true
let matchResult = "hello world".match(/hello/);
console.log(matchResult[0]); // "hello"
let execResult = /(\d+)/.exec("Price: 99");
console.log(execResult[1]); // "99"
Common Mistakes with Regular Expressions
- Forgetting escape characters – Special characters like
.
and `` need escaping. - Not using global (
g
) when needed – Without it,match()
returns only the first match. - Overusing regex for simple tasks – Sometimes
split()
,includes()
, orreplace()
is enough.
Regular expressions in JavaScript are a powerful tool for searching, replacing, and validating text. Mastering them helps with data processing, input validation, and text parsing.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.