Regular Expressions

Regular Expressions, or regex, are patterns used to match and manipulate strings. They are useful for tasks like searching, validating, or replacing text in a string.

What is a Regular Expression?

A regular expression is a sequence of characters that defines a search pattern. Think of it as a tool that can:

  • Find specific text.
  • Validate formats (like emails, phone numbers).
  • Replace parts of a string.

Basic Syntax

Regular expressions are written between two forward slashes (/) in JavaScript.

Javascript
Copy
let regex = /pattern/; // Example of a regex

How to Use Regex in JavaScript

JavaScript provides two main ways to use regular expressions:

  1. With RegExp methods (test, exec).
  2. With string methods (match, replace, search, split).

Common Regular Expression Methods

test()

Checks if a pattern exists in a string. Returns true or false.

Javascript
Copy
let regex = /hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("hi there")); // false

exec()

Finds and returns the first match as an object, or null if no match is found.

Javascript
Copy
let regex = /world/;
let result = regex.exec("hello world");
console.log(result); // ["world"]
console.log(result.index); // 6 (position of the match)

match()

Used with strings to return matches of a regex.

Javascript
Copy
let regex = /world/;
let result = regex.exec("hello world");
console.log(result); // ["world"]
console.log(result.index); // 6 (position of the match)

replace()

Replaces part of a string based on a pattern.

Javascript
Copy
let str = "hello world";
let result = str.replace(/world/, "JavaScript");
console.log(result); // "hello JavaScript"

search()

Finds the position of the first match, or -1 if not found.

Javascript
Copy
let str = "hello world";
console.log(str.search(/world/)); // 6
console.log(str.search(/JavaScript/)); // -1

split()

Splits a string into an array based on a pattern.

Javascript
Copy
let str = "apple, banana, cherry";
let result = str.split(/, /);
console.log(result); // ["apple", "banana", "cherry"]

Regex Syntax

Basic Characters

    /abc/ - Matches the exact sequence "abc".

    /hello/ - Matches "hello".

Special Characters

1. . (dot): Matches any single character.

Javscript
Copy
let regex = /h.llo/;
console.log(regex.test("hello")); // true
console.log(regex.test("hxllo")); // true

2. ^: Matches the start of a string.

Javascript
Copy
let regex = /^hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("world hello")); // false

3. $: Matches the end of a string.

Javascript
Copy
let regex = /world$/;
console.log(regex.test("hello world")); // true
console.log(regex.test("world hello")); // false

4. *: Matches 0 or more of the preceding character.

Javascript
Copy
let regex = /he*/;
console.log(regex.test("h")); // true
console.log(regex.test("heeeee")); // true

5. +: Matches 1 or more of the preceding character.

Javascript
Copy
let regex = /he+/;
console.log(regex.test("h")); // false
console.log(regex.test("heeeee")); // true

6. ?: Makes the preceding character optional.

Javascript
Copy
let regex = /colou?r/;
console.log(regex.test("color")); // true
console.log(regex.test("colour")); // true

7. |: Acts like "OR".

Javascript
Copy
let regex = /cat|dog/;
console.log(regex.test("I have a cat")); // true
console.log(regex.test("I have a dog")); // true

Character Sets

1. [abc]: Matches any one of the characters inside the brackets.

Javascript
Copy
let regex = /[aeiou]/;
console.log(regex.test("hello")); // true (matches 'e')
console.log(regex.test("sky")); // false

2. [^abc]: Matches any character NOT inside the brackets.

Javascript
Copy
let regex = /[^aeiou]/;
console.log(regex.test("sky")); // true (matches 's', 'k', or 'y')

3. [a-z]: Matches a range of characters.

Javascript
Copy
let regex = /[a-z]/;
console.log(regex.test("hello")); // true
console.log(regex.test("1234")); // false

Quantifiers

Quantifiers specify how many times a character or group should appear:

  • {n}: Exactly n times.
  • {n,}: At least n times.
  • {n,m}: Between n and m times.
Javascript
Copy
let regex = /a{2,4}/;
console.log(regex.test("aaa")); // true (matches 2-4 'a's)
console.log(regex.test("a")); // false

Escape Characters

To use special characters literally, escape them with a backslash (\):

Javascript
Copy
let regex = /\./;
console.log(regex.test("hello.")); // true
console.log(regex.test("hello")); // false

Real-World Examples

Validate an Email Address

Javascript
Copy
let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("example@gmail.com")); // true
console.log(emailRegex.test("not-an-email")); // false

Match a Phone Number

Javascript
Copy
let phoneRegex = /^\d{10}$/;
console.log(phoneRegex.test("1234567890")); // true
console.log(phoneRegex.test("123-456-7890")); // false

Replace All Whitespace

Javascript
Copy
let str = "Hello    world!";
let result = str.replace(/\s+/g, " ");
console.log(result); // "Hello world!"