Regular expressions (regex) let you search, validate, and replace text in strings. How they work in JavaScript.
What are regular expressions?
Regular expressions are patterns for matching character combinations in strings. In JavaScript they are RegExp objects, used for searching, replacing, and extracting text.
Syntax of regular expressions
A regular expression sits between slashes /:
let regex = /hello/;
This matches the string “hello” anywhere in a larger string.
Using regular expressions
Regex is commonly used with test, exec, match, replace, and search.
test()
test() checks whether a string matches a regex.
let pattern = /world/;
console.log(pattern.test('hello world')); // Outputs: true
exec()
exec() finds a match and returns an array containing the matched text.
let result = /hello/.exec('hello world');
console.log(result[0]); // Outputs: hello
Flags in regular expressions
Flags change how a regex searches:
g(global) – find all matches, not just the firsti(case-insensitive) – ignore letter casem(multiline) – treat^and$as line boundaries
Example – using flags:
let regex = /hello/gi;
Common use cases
Validating formats
Regex is useful for checking emails, phone numbers, URLs, and similar formats.
let emailPattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
let email = 'test@example.com';
console.log(emailPattern.test(email)); // Outputs: true
Extracting information
You can pull specific values out of a string – numbers, dates, and so on.
let text = 'The price is 100 dollars';
let pricePattern = /\d+/;
let price = text.match(pricePattern)[0];
console.log(price); // Outputs: 100
String replacement
Regex can replace parts of a string without manual slicing.
let text = 'JavaScript is fun';
let newText = text.replace(/fun/, 'awesome');
console.log(newText); // Outputs: JavaScript is awesome
Crafting regular expressions
Building regex takes practice. The main building blocks:
- Literals: the text to match (e.g.
/hello/). - Character classes: a set of characters to match (e.g.
\dfor any digit). - Quantifiers: how many characters (e.g.
+for one or more). - Anchors: position in the text (e.g.
^for the start).
Tips for using regular expressions
- Start simple: build up from basic patterns rather than writing something complex first.
- Testing: use tools like regex101.com to test and debug your expressions.
- Readability: complex regex is hard to read. Add comments or break it into smaller parts.
- Performance: overly complex regex can slow things down. Keep patterns as simple as they need to be.
Regex looks intimidating at first, but it is worth learning. Form validation, data extraction, and string cleanup all become much easier once you are comfortable with it.

