Codeskill

Learn to code, step by step

Regular expressions for real tasks

Regular expressions for real tasks – validating input, pulling bits out of strings, and replacing patterns. Not a full regex encyclopaedia, just the habits that save time.

Creating and testing

const emailPattern = /^[^s@]+@[^s@]+.[^s@]+$/;
emailPattern.test('alex@example.com'); // true

const text = 'Order #1042 shipped on 2026-07-28';
const match = text.match(/#(d+)/);
match[1]; // '1042'

Literals use /pattern/flags. Common flags: i case-insensitive, g global replace/match all, m multiline ^/$.

Groups and replace

const slug = 'Hello World!'.toLowerCase()
  .replace(/[^a-z0-9]+/g, '-')
  .replace(/(^-|-$)/g, '');
// 'hello-world'
'2026-07-28'.replace(/(d{4})-(d{2})-(d{2})/, '$3/$2/$1');
// '28/07/2026'

Named groups

const pattern = /(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/;
const { groups } = '2026-07-28'.match(pattern);
groups.day; // '28'

When regex is the wrong tool

HTML parsing, JSON, and full URLs are usually better handled with DOM APIs, JSON.parse, and the URL class. Regex works on plain strings with stable patterns – postcodes with known formats, log lines, slugify helpers.

Escape user input

function escapeRegex(text) {
  return text.replace(/[.*+?^${}()|[]\]/g, '\$&');
}

const term = escapeRegex(userInput);
const re = new RegExp(term, 'i');

If you build a regex from user search text, escape metacharacters or you will match more than you intended.

Next: testing JavaScript lightly – what to test first without turning the page into a framework tutorial.

PreviousBrowser storage (local, session, IndexedDB intro)