Skip to content

Intermediate · Map, Set, iterators, generators and regular expressions · topic 34 of 61 · 30 min

Regular expressions: the basics

Explanation

A regular expression (regex) is a pattern that describes text, used to test, find and replace. /^[6-9]\d{9}$/ means "a digit 6 to 9 followed by exactly nine more digits, and nothing else", which checks an Indian mobile number. Learn character classes, quantifiers, anchors and flags, and the methods test, match and replace.

Why regular expressions?

Many text jobs are about patterns, not exact words: "is this a 6-digit PIN code?", "find all amounts like ₹1,499", "remove extra spaces". You could write loops checking each character, but a regex describes the pattern in one short line. Every major language supports them with very similar syntax, so what you learn here works almost everywhere.

Writing a regex

javascript
const pin = /^[1-9][0-9]{5}$/;          // a literal between slashes
const word = new RegExp('chai', 'i');    // from a string (useful when the pattern is built at run time)
console.log(pin.test('560001'));  // true
console.log(pin.test('060001'));  // false (Indian PINs do not start with 0)
console.log(word.test('Masala CHAI')); // true (i flag: ignore case)

The building blocks

PatternMatches
abcthe exact text abc
.any one character except a new line
\d \w \sa digit / a word character (letter, digit, _) / a space, tab or new line
\D \W \SNOT a digit / word character / space
[aeiou]one of these characters
[0-9] [a-z]one character in the range
[^0-9]one character NOT in the set
^ $start / end of the text (anchors)
a|ba or b

Quantifiers: how many times

QuantifierMeaningExample
*0 or moreab*c matches ac, abc, abbc
+1 or more\d+ matches 7 or 2026
?0 or 1 (optional)colou?r matches color and colour
{n}exactly n\d{6} six digits
{n,m}between n and m\d{2,4}

Anchors matter for validation

javascript
const sixDigits = /\d{6}/;
console.log(sixDigits.test('PIN 5600019999')); // true: it FOUND six digits somewhere
const exactlySix = /^\d{6}$/;
console.log(exactlySix.test('5600019999'));    // false: the whole text must be six digits
Careful: For validation, always anchor the pattern with ^ at the start and $ at the end. Without anchors, test only checks whether the pattern appears anywhere, so "abc560001xyz" would pass a PIN check.

Flags

Flags come after the closing slash. g (global) finds all matches instead of the first; i ignores upper/lower case; m makes ^ and $ work on every line; u turns on full Unicode support. You can combine them: /chai/gi.

Using regex with strings

javascript
const text = 'Paid ₹250 for tea, ₹1200 for lunch';
console.log(/\d+/.test(text));            // true
console.log(text.match(/\d+/));            // ['250', index: 6, …] (first match with details)
console.log(text.match(/\d+/g));           // ['250', '1200'] (all matches)
console.log(text.replace(/\d+/g, 'XX'));   // 'Paid ₹XX for tea, ₹XX for lunch'
console.log('a,  b ,c'.split(/\s*,\s*/));  // ['a', 'b', 'c']

Real Indian validations

javascript
const mobile = /^[6-9]\d{9}$/;            // 10 digits, starting 6–9
const pinCode = /^[1-9][0-9]{5}$/;         // 6 digits, not starting with 0
const ifsc = /^[A-Z]{4}0[A-Z0-9]{6}$/;     // e.g. SBIN0001234: 4 letters, 0, 6 letters/digits
console.log(mobile.test('9876543210'), pinCode.test('110001'), ifsc.test('SBIN0001234')); // true true true
Think of it like this: A regex is like the shape-sorter toy for children: a pattern of holes. Text either fits through the holes or it does not. ^ and $ are like insisting the block fills the hole completely, with nothing sticking out.
Tip: Build and test patterns step by step with sample inputs, including ones that should FAIL. Online testers like regex101.com explain each part of a pattern; remember to choose the JavaScript flavour there.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Regular expressions: the basics · 1/7

Regular expressions

In this lesson you will describe text patterns with regular expressions.

Prefer a video by a teacher? Find free videos on “javascript regular expressions tutorial for beginners” on YouTube ↗

In real life: Validating a KYC form

A fintech app collects mobile number, PIN code and bank IFSC during sign-up. Each field is checked with a regex on the phone before sending, which gives instant feedback. The server checks again, because browser checks can be bypassed.

javascript
const rules = { mobile: /^[6-9]\d{9}$/, pin: /^[1-9]\d{5}$/, ifsc: /^[A-Z]{4}0[A-Z0-9]{6}$/ };
const form = { mobile: '9123456789', pin: '0400012', ifsc: 'HDFC0001234' };
const errors = Object.keys(rules).filter((field) => !rules[field].test(form[field]));
console.log(errors); // ['pin']

Practice (0/3 done)

Task 1 · Code · Javascript

Write isValidPin(text) that returns true only for a 6-digit Indian PIN code that does not start with 0.

Task 2 · Code · Javascript

Write isValidMobile(text) for Indian mobile numbers: optionally starting with "+91" or "0", then 10 digits where the first is 6, 7, 8 or 9. Spaces are not allowed.

Task 3 · Code · Javascript

Write extractAmounts(text) that returns all whole-number amounts written after "Rs" or "₹" (with an optional space), as numbers. "Paid Rs 250 and ₹1200, tip Rs40" gives [250, 1200, 40].

Quick quiz

Question 1

1.What does \d+ match?

Question 2

2.Why does /\d{6}/.test('abc560001xyz') return true?

Question 3

3.What does 'a1b22c333'.match(/\d+/g) give?

Question 4

4.Which flag makes a regex ignore upper/lower case?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does \d+ match?

Answer: One or more digits

+ means one or more of the thing before it.

Why does /\d{6}/.test('abc560001xyz') return true?

Answer: Without ^ and $ the pattern can match anywhere in the text

Unanchored patterns find a match anywhere.

What does 'a1b22c333'.match(/\d+/g) give?

Answer: ['1', '22', '333']

With g, match returns every run of digits.

Which flag makes a regex ignore upper/lower case?

Answer: i

i stands for case-insensitive.

Why write regex patterns as raw strings like r"..."?Related

Answer: So Python passes every backslash to re unchanged

In normal strings some backslash pairs have special meanings, like \b for backspace. A raw string keeps them as written.

From JSON and regular expressions

What do ^ and $ do in a regex?Related

Answer: Mark the start and the end of the text

Anchors make the whole text match, not just a piece of it.

From Validating input

What is 'ab12'.match(/([a-z]+)(\d+)/)[2]?Related

Answer: '12'

Group 2 is the second bracket: the digits.

From Regular expressions in practice

What does pattern="[0-9]{6}" accept?Related

Answer: Exactly six digits

[0-9] is one digit and {6} means exactly six, and the pattern must match the whole value.

From Built-in form validation

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Map, Set, iterators, generators and regular expressions” before its exam: Regular expressions in practice.
  2. Module 7 exam: Collections, iterators and regular expressions · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Asynchronous JavaScript. 61 topics left in the course before the final exam.

← Previous: Generators