JavaScript · Lesson 26 / 32 · English
Regular Expressions
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
A regular expression describes a text pattern. Anchors match boundaries; character classes describe allowed characters; quantifiers specify repetition.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Regular Expressions (RegExp)
Regular expressions are patterns used to match character combinations in strings. They are powerful for validation, searching, and replacing.
Creating RegExp
// Literal syntax (preferred)
const re1 = /hello/;
const re2 = /hello/gi; // flags: g=global, i=case-insensitive
// Constructor (for dynamic patterns)
const pattern = "hello";
const re3 = new RegExp(pattern, "gi");Common Patterns
| Pattern | Meaning | Example Match |
|---|---|---|
| . | Any character except newline | a, 1, ! |
| \d | Digit [0-9] | 5 |
| \w | Word char [a-zA-Z0-9_] | a, Z, 3 |
| \s | Whitespace | space, tab |
| ^ | Start of string | ^Hello matches "Hello World" |
| $ | End of string | World$ matches "Hello World" |
| + | One or more | \d+ matches "123" |
| * | Zero or more | \d* matches "" or "123" |
| ? | Zero or one | colou?r matches color/colour |
| {n,m} | Between n and m times | \d{2,4} matches 2-4 digits |
| [abc] | Any of a, b, or c | gr[ae]y matches gray/grey |
| (a|b) | a or b | cat|dog matches cat or dog |
Using RegExp with Strings
const text = "Hello World, hello JavaScript!";
// test — returns boolean
/hello/i.test(text); // true
// match — returns matches
text.match(/hello/gi); // ["Hello", "hello"]
text.match(/(\w+)World/); // with capture groups
// matchAll — returns iterator of all matches
const matches = [...text.matchAll(/hello/gi)];
// replace
text.replace(/hello/i, "Hi"); // replaces first
text.replace(/hello/gi, "Hi"); // replaces all
text.replaceAll("hello", "Hi"); // string replaceAll
// search — returns index of first match
text.search(/World/); // 6
// split
"a1b2c3".split(/\d/); // ["a", "b", "c", ""]
// Real-world examples
const emailRe = /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i;
console.log(emailRe.test("user@example.com")); // true
const phoneRe = /^\+?[\d\s-]{10,15}$/;
console.log(phoneRe.test("+1 555-0123")); // trueA complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
const courseCode = /^JS-\d{3}$/;
console.log(courseCode.test("JS-101"));
console.log(courseCode.test("JS-12"));
console.log("Lesson 12".replace(/\d+/g, "13"));Predict first. Reveal the expected result.
true false Lesson 13
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Test JS-999 and XJS-101.
Reveal the answer and reasoning
JS-999 matches; XJS-101 does not because ^ anchors the start.
One mistake to avoid: Do not use a simple regex as your only validation for complex formats or security rules. Patterns with g can also carry lastIndex state when reused with test.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.