JavaScript Tutorial menu

JavaScript Regular Expressions

A regular expression (regex) is a pattern that describes text. You use it to search, check or replace text.

Writing a Pattern

A regex is written between two slashes, with optional flags after it:

Example

javascript
const pattern = /karachi/i;   // i = ignore upper/lower case

console.log(pattern.test("I live in Karachi"));   // true
console.log(pattern.test("I live in Lahore"));    // false

test() returns true if the pattern is found anywhere in the text.

Flags

FlagMeaning
iIgnore case: A and a match each other
gGlobal: find all matches, not only the first
mMultiline: ^ and $ work on each line
uUnicode: handles emoji and non-English letters correctly

Building Blocks

These are the pieces you will use most:

PatternMatches
abcThe exact text "abc"
.Any single character (except a new line)
\dA digit, 0 to 9
\wA letter, digit or underscore
\sA space, tab or new line
[aeiou]Any one of these characters
[a-z]Any character in the range
[^0-9]Any character not in the brackets
^The start of the text
$The end of the text

A pipe between two patterns means "or": /cat|dog/ matches either "cat" or "dog".

How Many Times?

Quantifiers say how many times the thing before them may repeat:

QuantifierMeans
*0 or more
+1 or more
?0 or 1 (optional)
{4}Exactly 4
{2,5}Between 2 and 5
{2,}2 or more

So \d{4} means "four digits", and colou?r matches both "color" and "colour".

Checking a Pakistani Mobile Number

A mobile number like 0300-1234567 is: 03, two digits, an optional dash, then seven digits. ^ and $ make sure the whole text matches, not just part of it.

Example

html
<!DOCTYPE html>
<html>
<body>

<input id="phone" placeholder="0300-1234567">
<button id="check">Check</button>
<p id="msg"></p>

<script>
const mobile = /^03\d{2}-?\d{7}$/;

document.getElementById("check").addEventListener("click", () => {
  const value = document.getElementById("phone").value.trim();
  document.getElementById("msg").textContent = mobile.test(value)
    ? "Valid number: " + value
    : "Please enter a number like 0300-1234567";
});
</script>

</body>
</html>
Try it Yourself »

Try 03001234567, 0300-1234567, 0300-123 and 1234.

Finding Matches

match() with the g flag returns an array of every match:

Example

javascript
const sms = "Your order of Rs 1200 is ready. Delivery charge Rs 150. Total Rs 1350.";
const amounts = sms.match(/\d+/g);
console.log(amounts);
Output
[ '1200', '150', '1350' ]

Without g, match() returns only the first match, with extra details. If nothing matches, it returns null.

Replacing Text

replace() and replaceAll() accept a regex:

Example

javascript
const text = "Call  me   at    0321 5550000";
console.log(text.replace(/\s+/g, " "));      // many spaces become one

const card = "4111-2222-3333-4444";
console.log(card.replace(/\d{4}(?=-)/g, "****"));
Output
Call me at 0321 5550000
****-****-****-4444

(?=-) is a lookahead: it means "followed by a dash", without including the dash in the match. So only the first three groups are hidden.

Capture Groups

Round brackets ( ) capture part of the match, so you can read it on its own. You can also name a group with (?<name>...):

Example

html
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const datePattern = /(?<day>\d{2})\/(?<month>\d{2})\/(?<year>\d{4})/;
const result = "Admission date: 05/11/2026".match(datePattern);

const { day, month, year } = result.groups;

document.getElementById("demo").innerHTML =
  "Full match: " + result[0] + "<br>" +
  "Day: " + day + ", Month: " + month + ", Year: " + year + "<br>" +
  "ISO format: " + year + "-" + month + "-" + day;
</script>

</body>
</html>
Try it Yourself »
Output
Full match: 05/11/2026
Day: 05, Month: 11, Year: 2026
ISO format: 2026-11-05

In replace(), you can use $1, $2 (or $<name>) to put a group back into the new text:

Example

javascript
console.log("Khan, Ayesha".replace(/(\w+), (\w+)/, "$2 $1"));   // Ayesha Khan

Escaping Special Characters

Characters like . * + ? ( ) [ ] { } / \ ^ $ | have special meanings. To match them as normal text, put a backslash before them: \. matches a real dot, and \$ matches a real dollar sign.

Regex can get hard to read fast. Keep patterns short, write a comment explaining each one, and test them with many sample inputs, both good and bad.

Exercise

Exercise

Which regex matches text that is exactly five digits, like "75300"?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp