How to use RegExp object in JavaScript

15 Answers

0 votes
// ==================================================
// Title: Creating a RegExp Object
// ==================================================
//
// A RegExp object represents a regular expression.
//
// There are two common ways to create one:
// 1. Regular expression literal
// 2. RegExp constructor
//

/*
   JavaScript RegExp Best Practices:

// Store reusable patterns in constants.
const emailPattern =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Use descriptive variable names.
const phonePattern =
    /^\d{10}$/;

// Always check for null when using exec().
const match =
    emailPattern.exec("alice@example.com");

if (match !== null) {
    console.log(match[0]);
}

// Use named capture groups when patterns
// become complex and readability matters.

// Avoid creating RegExp objects repeatedly
// inside loops when a reusable pattern will do.
*/

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

const email = "c-3po@example.com";

console.log(emailPattern.test(email));



/*
run:

true

*/

 



answered Oct 11 by avibootz
edited Oct 11 by avibootz
0 votes
// ==================================================
// Title: Using test()
// ==================================================
//
// test() checks whether a string matches
// a regular expression.
//
// It returns true or false.
//

const digitPattern = /\d+/;

console.log(digitPattern.test("12345"));
console.log(digitPattern.test("Hello"));


/*
run:

true
false

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Using exec()
// ==================================================
//
// exec() returns detailed match information.
//
// If there is no match, it returns null.
//

const pattern = /\d+/;

const text = "Order number: 12345";

const match = pattern.exec(text);

if (match !== null) {
    console.log("Matched value:", match[0]);
    console.log("Found at index:", match.index);
}


/*
run:

Matched value: 12345
Found at index: 14

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Extracting Multiple Matches
// ==================================================
//
// The g flag enables global searching.
//
// match() returns all matching values.
//

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

const pattern = /\d+/g;

const matches = text.match(pattern);

console.log(matches);



/*
run:

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

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Replacing Text
// ==================================================
//
// replace() can replace all matching text.
//
// The 'g' flag makes the replacement global.
// The 'i' flag makes it case-insensitive.
//

const sentence =
    "Red apples are red.";

const pattern = /red/gi;

const result =
    sentence.replace(pattern, "blue");

console.log(result);


/*
run:

blue apples are blue.

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Splitting with Regular Expressions
// ==================================================
//
// split() accepts a regular expression.
//
// This example separates values using commas
// and optional spaces.
//

// Splitting Strings

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

const separator = /,\s*/;

const fruits = input.split(separator);

console.log(fruits);


/*
run:

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

*/

 



answered Oct 11 by avibootz
0 votes
// ========================================================
// Title: Capturing Groups
// ========================================================

/*
 Parentheses create capture groups.

 This example extracts parts of a date.
*/
const datePattern =
    /^(\d{4})-(\d{2})-(\d{2})$/;

const date = "2026-10-10";
const match = datePattern.exec(date);

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

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


/*
run:

2026
10
10

*/

 



answered Oct 11 by avibootz
0 votes
// ========================================================
// Title: Username Validation
// ========================================================
//
// Rules:
// - 3 to 16 characters
// - letters, digits, underscore only
//
const usernamePattern =
    /^[A-Za-z0-9_]{3,16}$/;

const username = "dumbledore_123";

const isValid =
    usernamePattern.test(username);

console.log(isValid);


/*
run:

true

*/

 



answered Oct 11 by avibootz
0 votes
// ========================================================
// Title: Named Capture Groups
// ========================================================
//
// Named groups make code easier to read.
//
const pattern =
    /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;

const input = "2026-10-10";

const match = pattern.exec(input);

if (
    match !== null &&
    match.groups
) {
    console.log(match.groups.year);
    console.log(match.groups.month);
    console.log(match.groups.day);
}


/*
run:

2026
10
10

*/

 



answered Oct 11 by avibootz
0 votes
// ========================================================
// Title: Using matchAll()
// ========================================================
//
// matchAll() returns an iterator containing
// detailed information about every match.
//

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

const pattern = /\d+/g;

for (const match of text.matchAll(pattern)) {
    console.log(
        `Value: ${match[0]}, Index: ${match.index}`
    );
}


/*
run:

Value: 101, Index: 5
Value: 202, Index: 10
Value: 303, Index: 15

*/

 



answered Oct 11 by avibootz
0 votes
// ========================================================
// Title: Extracting URLs
// ========================================================
//
// Regular expressions are often used to locate
// structured patterns inside text.
//

const text = 'Visit https://example.com or https://test.com';

const urlPattern =
    /https?:\/\/[^\s]+/g;

const urls = text.match(urlPattern);

console.log(urls);


/*
run:

[ 'https://example.com', 'https://test.com' ]

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Building a RegExp Dynamically
// ==================================================
//
// The RegExp constructor allows patterns
// to be created at runtime.
//

// Dynamic Regular Expressions

const keyword = "JavaScript";

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

const text = "I enjoy learning javascript.";

console.log(pattern.test(text));


/*
run:

true

*/

 



answered Oct 11 by avibootz
0 votes
// ==================================================
// Title: Parsing Log Entries
// ==================================================
//
// Regular expressions are useful for extracting
// structured information from text.
//

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

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

const match = pattern.exec(logLine);

if (match !== null) {
    const logEntry = {
        level: match[1],
        message: match[2]
    };

    console.log(logEntry);
}


/*
run:

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

*/

 



answered Oct 11 by avibootz

Related questions

1 answer 177 views
1 answer 190 views
1 answer 215 views
...