Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to use RegExp object in TypeScript

14 Answers

0 votes
// ==================================================
// Title: Creating a RegExp Object
// ==================================================
//
// A RegExp object represents a regular expression.
//
// It can be created using:
// 1. A regular expression literal
// 2. The RegExp constructor
//

/*
  TypeScript RegExp Best Practices:

// Use explicit RegExp types.
const emailPattern: RegExp =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Use meaningful variable names.
const phoneNumberPattern: RegExp =
    /^\d{10}$/;

// Keep patterns focused and readable.

// Prefer named capture groups for complex
// expressions when supported.

// Reuse compiled patterns instead of creating
// new RegExp objects inside loops.

// Always handle null when using exec().

const result: RegExpExecArray | null =
    emailPattern.exec("name@example.com");

if (result !== null) {
    console.log(result[0]);
}
*/

const emailPattern: RegExp =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const text: string = "bex@example.com";

const isValid: boolean =
    emailPattern.test(text);

console.log(isValid);


/*
run:

true

*/

 



answered 5 days ago by avibootz
edited 5 days ago by avibootz
0 votes
// ==================================================
// Title: Using test()
// ==================================================
//
// test() returns true if the text matches
// the pattern; otherwise false.
//

const pattern: RegExp = /\d+/;

const input1: string = "123";
const input2: string = "ABC";

const result1: boolean =
    pattern.test(input1);

const result2: boolean =
    pattern.test(input2);

console.log(result1);
console.log(result2);


/*
run:

true
false

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Using exec()
// ==================================================
//
// exec() returns detailed match information.
//
// If no match is found, it returns null.
//

const pattern: RegExp = /\d+/;

const text: string =
    "Order number: 12345";

const match: RegExpExecArray | null =
    pattern.exec(text);

if (match !== null) {
    console.log("Match:", match[0]);
    console.log("Index:", match.index);
}


/*
run:

Match: 12345
Index: 14

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Extracting Multiple Matches
// ==================================================
//
// The g flag enables global matching.
//
// match() returns an array of matches
// or null if no matches are found.
//

// Extracting All Matches

const text: string =
    "Product IDs: 101, 202, 303";

const pattern: RegExp = /\d+/g;

const matches: string[] | null =
    text.match(pattern);

console.log(matches);


/*
run:

[ '101', '202', '303' ]

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Username Validation
// ==================================================
//
// Rules:
// - 3 to 16 characters
// - letters, digits, underscore only
//

const usernamePattern: RegExp =
    /^[A-Za-z0-9_]{3,16}$/;

const username: string =
    "echo_123";

const isValidUsername: boolean =
    usernamePattern.test(username);

console.log(isValidUsername);


/*
run:

true

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Replacing Text
// ==================================================
//
// replace() can use a regular expression
// to find text and substitute new values.
//

const sentence: string =
    "The color is red. Red is popular.";

const pattern: RegExp = /red/gi;

const updatedSentence: string =
    sentence.replace(pattern, "blue");

console.log(updatedSentence);


/*
run:

The color is blue. blue is popular.

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Splitting Text with RegExp
// ==================================================
//
// split() accepts a regular expression.
//
// This example splits on commas and whitespace.
//

const input: string =
    "apple, banana, orange, grape";

const separator: RegExp = /,\s*/;

const fruits: string[] =
    input.split(separator);

console.log(fruits);


/*
run:

[ 'apple', 'banana', 'orange', 'grape' ]

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Finding Capitalized Words
// ==================================================
//
// Match words beginning with an uppercase
// letter followed by lowercase letters.
//

// Finding Words That Start with a Capital Letter

const text: string =
    "Freya visited Paris with Bob";

const pattern: RegExp =
    /\b[A-Z][a-z]+\b/g;

const matches: string[] | null =
    text.match(pattern);

console.log(matches);


/*
run:

[ 'Freya', 'Paris', 'Bob' ]

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Capturing Groups
// ==================================================
//
// Parentheses create capture groups.
//
// This example extracts year, month,
// and day from a date string.
//

// Using Match Groups

const dateText: string =
    "2026-10-10";

const datePattern: RegExp =
    /^(\d{4})-(\d{2})-(\d{2})$/;

const match: RegExpExecArray | null =
    datePattern.exec(dateText);

if (match !== null) {
    const year: string = match[1];
    const month: string = match[2];
    const day: string = match[3];

    console.log(year);
    console.log(month);
    console.log(day);
}


/*
run:

2026
10
10

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Named Capture Groups
// ==================================================
//
// Named groups improve readability.
//
// The names can be accessed through the
// groups property.
//

const timestamp: string =
    "2026-10-10";

const pattern: RegExp =
    /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;

const match: RegExpExecArray | null =
    pattern.exec(timestamp);

if (
    match !== null &&
    match.groups !== undefined
) {
    const year: string =
        match.groups.year;

    const month: string =
        match.groups.month;

    const day: string =
        match.groups.day;

    console.log(year);
    console.log(month);
    console.log(day);
}


/*
run:

2026
10
10

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Creating RegExp Dynamically
// ==================================================
//
// The RegExp constructor allows patterns
// to be built at runtime.
//

// Dynamic Regular Expressions

const keyword: string = "TypeScript";

const pattern: RegExp = new RegExp(keyword, "i");

const text: string = "I enjoy learning typescript.";

const found: boolean = pattern.test(text);

console.log(found);



/*
run:

true

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Using matchAll()
// ==================================================
//
// matchAll() returns an iterator that
// exposes detailed match information.
//

// Iterating with matchAll()

const text: string =
    "IDs: 101, 202, 303";

const pattern: RegExp = /\d+/g;

const matches: IterableIterator<
    RegExpMatchArray
> = text.matchAll(pattern);

for (const match of matches) {
    console.log(
        `Found ${match[0]} at index ${match.index}`
    );
}


/*
run:

Found 101 at index 5
Found 202 at index 10
Found 303 at index 15

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Parsing Log Entries
// ==================================================
//
// Regular expressions are often useful for
// extracting structured data from text.
//

interface LogEntry {
    level: string;
    message: string;
}

const logLine: string = "[ERROR] Database connection failed";

const pattern: RegExp = /^\[(\w+)\]\s(.+)$/;

const match: RegExpExecArray | null = pattern.exec(logLine);

if (match !== null) {

    const entry: LogEntry = {
        level: match[1],
        message: match[2]
    };

    console.log(entry);
}


/*
run:

{ level: 'ERROR', message: 'Database connection failed' }

*/

 



answered 5 days ago by avibootz

Related questions

...