javascript

examples

examples.js
/**
 * ========================================
 * 13.2 Regular Expressions - Examples
 * ========================================
 *
 * Comprehensive examples of JavaScript regex.
 */

/**
 * EXAMPLE 1: Creating Regular Expressions
 *
 * Two ways to create regex patterns.
 */

// Literal notation (preferred for static patterns)
const literal = /hello/;
const withFlags = /hello/gi;

// Constructor (for dynamic patterns)
const constructor = new RegExp('hello');
const withFlagsConstructor = new RegExp('hello', 'gi');

// Dynamic pattern from variable
const searchTerm = 'world';
const dynamic = new RegExp(searchTerm, 'i');

console.log('Test literal:', literal.test('hello world')); // true
console.log('Test dynamic:', dynamic.test('Hello World')); // true

// Escaping special characters in constructor
const specialPattern = new RegExp('price: \\$\\d+'); // Need to escape \
console.log('Special:', specialPattern.test('price: $100')); // true

/**
 * EXAMPLE 2: Flags
 */

const text = `Hello World
hello world
HELLO WORLD`;

// No flags - case sensitive, first match
console.log('No flags:', text.match(/hello/));
// ['hello', index: 12]

// g flag - all matches
console.log('g flag:', text.match(/hello/g));
// ['hello']

// i flag - case insensitive
console.log('i flag:', text.match(/hello/i));
// ['Hello']

// gi flags - case insensitive, all matches
console.log('gi flags:', text.match(/hello/gi));
// ['Hello', 'hello', 'HELLO']

// m flag - multiline
console.log('m flag (^ each line):', text.match(/^hello/gim));
// ['Hello', 'hello', 'HELLO']

/**
 * EXAMPLE 3: Character Classes
 */

const str = 'abc123XYZ!@#';

// Custom character class
console.log('[abc]:', str.match(/[abc]/g)); // ['a', 'b', 'c']
console.log('[^abc]:', str.match(/[^abc]/g)); // ['1', '2', '3', 'X', ...]

// Ranges
console.log('[a-z]:', str.match(/[a-z]/g)); // ['a', 'b', 'c']
console.log('[A-Z]:', str.match(/[A-Z]/g)); // ['X', 'Y', 'Z']
console.log('[0-9]:', str.match(/[0-9]/g)); // ['1', '2', '3']

// Shorthand classes
console.log('\\d:', str.match(/\d/g)); // ['1', '2', '3']
console.log('\\D:', str.match(/\D/g)); // ['a', 'b', ..., '!', '@', '#']
console.log('\\w:', str.match(/\w/g)); // All letters and digits
console.log('\\W:', str.match(/\W/g)); // ['!', '@', '#']

/**
 * EXAMPLE 4: Quantifiers
 */

const testStr = 'goooood morning!';

// Basic quantifiers
console.log('o?:', 'gd god good goood'.match(/go?d/g)); // ['gd', 'god']
console.log('o*:', 'gd god good goood'.match(/go*d/g)); // ['gd', 'god', 'good', 'goood']
console.log('o+:', 'gd god good goood'.match(/go+d/g)); // ['god', 'good', 'goood']

// Specific counts
console.log('{2}:', testStr.match(/o{2}/g)); // ['oo', 'oo']
console.log('{2,4}:', testStr.match(/o{2,4}/g)); // ['oooo', 'oo']
console.log('{2,}:', testStr.match(/o{2,}/g)); // ['ooooo']

// Greedy vs non-greedy
const html = '<div>content</div>';
console.log('Greedy:', html.match(/<.*>/g)); // ['<div>content</div>']
console.log('Non-greedy:', html.match(/<.*?>/g)); // ['<div>', '</div>']

/**
 * EXAMPLE 5: Anchors and Boundaries
 */

const lines = `first line
second line
third line`;

// Start and end
console.log('^first:', 'first line'.match(/^first/)); // ['first']
console.log('^second:', 'first line'.match(/^second/)); // null

console.log('line$:', 'first line'.match(/line$/)); // ['line']
console.log('^line$:', 'line'.match(/^line$/)); // ['line']

// Multi-line mode
console.log('^...line (m):', lines.match(/^\w+ line/gm));
// ['first line', 'second line', 'third line']

// Word boundaries
const sentence = 'The cat scattered the category';
console.log('\\bcat\\b:', sentence.match(/\bcat\b/g)); // ['cat']
console.log('cat:', sentence.match(/cat/g)); // ['cat', 'cat', 'cat']

/**
 * EXAMPLE 6: Groups and Capturing
 */

// Capturing groups
const datePattern = /(\d{4})-(\d{2})-(\d{2})/;
const dateMatch = '2024-01-15'.match(datePattern);
console.log('Full match:', dateMatch[0]); // '2024-01-15'
console.log('Year:', dateMatch[1]); // '2024'
console.log('Month:', dateMatch[2]); // '01'
console.log('Day:', dateMatch[3]); // '15'

// Named groups
const namedPattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const namedMatch = '2024-01-15'.match(namedPattern);
console.log('Named groups:', namedMatch.groups);
// { year: '2024', month: '01', day: '15' }

// Non-capturing groups
const urlPattern = /(?:https?):\/\/(.+)/;
const urlMatch = 'https://example.com'.match(urlPattern);
console.log('URL match:', urlMatch[1]); // 'example.com' (not 'https')

// Backreferences
const repeated = /(\w+)\s+\1/;
console.log('Repeated:', 'the the'.match(repeated)); // ['the the', 'the']
console.log('Not repeated:', 'the cat'.match(repeated)); // null

/**
 * EXAMPLE 7: Alternation
 */

// Simple alternation
console.log('cat|dog:', 'I have a cat'.match(/cat|dog/)); // ['cat']
console.log('cat|dog:', 'I have a dog'.match(/cat|dog/)); // ['dog']

// Group alternation
console.log('gr(a|e)y:', 'gray'.match(/gr(a|e)y/)); // ['gray', 'a']
console.log('gr(a|e)y:', 'grey'.match(/gr(a|e)y/)); // ['grey', 'e']

// Multiple options
const colors = /\b(red|green|blue|yellow)\b/gi;
console.log('Colors:', 'Red car, blue sky'.match(colors));
// ['Red', 'blue']

/**
 * EXAMPLE 8: Lookahead and Lookbehind
 */

// Positive lookahead - match if followed by
const lookahead = /hello(?= world)/;
console.log('Lookahead:', 'hello world'.match(lookahead)); // ['hello']
console.log('No match:', 'hello there'.match(lookahead)); // null

// Negative lookahead - match if NOT followed by
const negLookahead = /hello(?! world)/;
console.log('Neg lookahead:', 'hello there'.match(negLookahead)); // ['hello']
console.log('No match:', 'hello world'.match(negLookahead)); // null

// Positive lookbehind - match if preceded by
const lookbehind = /(?<=\$)\d+/;
console.log('Lookbehind:', '$100'.match(lookbehind)); // ['100']
console.log('No match:', '100'.match(lookbehind)); // null

// Negative lookbehind - match if NOT preceded by
const negLookbehind = /(?<!\$)\d+/;
console.log('Neg lookbehind:', 'price 100'.match(negLookbehind)); // ['100']
console.log('No match (with $):', '$100'.match(negLookbehind)); // null (matches '00')

/**
 * EXAMPLE 9: test() Method
 */

const emailPattern = /^[\w.-]+@[\w.-]+\.\w{2,}$/;

console.log('Valid email:', emailPattern.test('user@example.com')); // true
console.log('Invalid email:', emailPattern.test('invalid.email')); // false

// Simple validation
function isValidEmail(email) {
  return /^[\w.-]+@[\w.-]+\.\w{2,}$/.test(email);
}

console.log('Check:', isValidEmail('test@test.com')); // true

/**
 * EXAMPLE 10: match() vs matchAll()
 */

const str2 = 'test1 test2 test3';

// match with g flag - returns array of matches
console.log('match:', str2.match(/test\d/g));
// ['test1', 'test2', 'test3']

// matchAll - returns iterator with details
const matches = [...str2.matchAll(/test(\d)/g)];
console.log('matchAll:');
matches.forEach((match) => {
  console.log(`  Full: ${match[0]}, Group: ${match[1]}, Index: ${match.index}`);
});
// Full: test1, Group: 1, Index: 0
// Full: test2, Group: 2, Index: 6
// Full: test3, Group: 3, Index: 12

/**
 * EXAMPLE 11: replace() with Regex
 */

// Simple replacement
console.log('Replace:', 'hello world'.replace(/world/, 'there'));
// 'hello there'

// Global replacement
console.log('Replace all:', 'hello hello'.replace(/hello/g, 'hi'));
// 'hi hi'

// Case-insensitive
console.log('Case-insensitive:', 'Hello HELLO'.replace(/hello/gi, 'hi'));
// 'hi hi'

// Using capture groups
console.log('Swap name:', 'John Doe'.replace(/(\w+) (\w+)/, '$2, $1'));
// 'Doe, John'

// Named groups in replacement
console.log(
  'Named:',
  'John Doe'.replace(/(?<first>\w+) (?<last>\w+)/, '$<last>, $<first>')
);
// 'Doe, John'

// Replacement function
const prices = 'Item: $10, Tax: $2';
const doubled = prices.replace(/\$(\d+)/g, (match, amount) => {
  return '$' + parseInt(amount) * 2;
});
console.log('Doubled prices:', doubled);
// 'Item: $20, Tax: $4'

// Complex replacement function
const text3 = 'hello world';
const titled = text3.replace(/\b\w/g, (char) => char.toUpperCase());
console.log('Titled:', titled);
// 'Hello World'

/**
 * EXAMPLE 12: split() with Regex
 */

// Split on pattern
console.log('Split spaces:', 'a   b  c'.split(/\s+/));
// ['a', 'b', 'c']

console.log('Split multiple:', 'a,b;c:d'.split(/[,;:]/));
// ['a', 'b', 'c', 'd']

// Keep separators
console.log('Keep seps:', 'a1b2c3'.split(/(\d)/));
// ['a', '1', 'b', '2', 'c', '3', '']

// Limit splits
console.log('Limit:', 'a,b,c,d,e'.split(/,/, 3));
// ['a', 'b', 'c']

/**
 * EXAMPLE 13: exec() for Iteration
 */

const pattern = /\d+/g;
const str3 = 'a1b22c333';

let match;
console.log('exec iteration:');
while ((match = pattern.exec(str3)) !== null) {
  console.log(`  Found: ${match[0]} at index ${match.index}`);
}
// Found: 1 at index 1
// Found: 22 at index 3
// Found: 333 at index 6

/**
 * EXAMPLE 14: Common Patterns
 */

// Email validation
const email = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
console.log('Email valid:', email.test('user@example.com'));

// URL validation
const url = /^https?:\/\/[\w.-]+(?:\/[\w.-]*)*\/?(?:\?[\w=&]*)?$/;
console.log('URL valid:', url.test('https://example.com/path?q=1'));

// Phone number (US)
const phone = /^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;
console.log('Phone valid:', phone.test('(555) 123-4567'));

// Date (YYYY-MM-DD)
const date = /^\d{4}-\d{2}-\d{2}$/;
console.log('Date valid:', date.test('2024-01-15'));

// Hex color
const hexColor = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
console.log('Hex valid:', hexColor.test('#ff5733'));

// IP address (basic)
const ip = /^(?:\d{1,3}\.){3}\d{1,3}$/;
console.log('IP valid:', ip.test('192.168.1.1'));

// Password (min 8, upper, lower, digit)
const password = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log('Password valid:', password.test('Password123'));

/**
 * EXAMPLE 15: Extract Information
 */

// Extract all numbers
const textWithNums = 'There are 42 apples and 17 oranges';
const numbers = textWithNums.match(/\d+/g)?.map(Number);
console.log('Numbers:', numbers); // [42, 17]

// Extract hashtags
const tweet = 'Learning #JavaScript and #RegEx today! #coding';
const hashtags = tweet.match(/#\w+/g)?.map((tag) => tag.slice(1));
console.log('Hashtags:', hashtags); // ['JavaScript', 'RegEx', 'coding']

// Extract URLs
const textWithUrls = 'Visit https://example.com and http://test.com';
const urls = textWithUrls.match(/https?:\/\/[\w.-]+/g);
console.log('URLs:', urls); // ['https://example.com', 'http://test.com']

// Extract email addresses
const textWithEmails = 'Contact user@example.com or admin@test.org';
const emails = textWithEmails.match(/[\w.-]+@[\w.-]+\.\w+/g);
console.log('Emails:', emails); // ['user@example.com', 'admin@test.org']

/**
 * EXAMPLE 16: Validate and Parse
 */

// Parse date
function parseDate(dateStr) {
  const pattern = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
  const match = dateStr.match(pattern);

  if (!match) return null;

  return {
    year: parseInt(match.groups.year),
    month: parseInt(match.groups.month),
    day: parseInt(match.groups.day),
  };
}
console.log('Parse date:', parseDate('2024-01-15'));
// { year: 2024, month: 1, day: 15 }

// Parse time
function parseTime(timeStr) {
  const pattern =
    /^(?<hours>\d{1,2}):(?<minutes>\d{2})(?::(?<seconds>\d{2}))?(?:\s*(?<period>AM|PM))?$/i;
  const match = timeStr.match(pattern);

  if (!match) return null;

  return match.groups;
}
console.log('Parse time:', parseTime('2:30:45 PM'));
// { hours: '2', minutes: '30', seconds: '45', period: 'PM' }

/**
 * EXAMPLE 17: Replace Patterns
 */

// Mask credit card
function maskCreditCard(number) {
  return number.replace(/\d(?=\d{4})/g, '*');
}
console.log('Masked CC:', maskCreditCard('1234567890123456'));
// '************3456'

// Format phone number
function formatPhone(phone) {
  const cleaned = phone.replace(/\D/g, '');
  return cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
console.log('Formatted phone:', formatPhone('5551234567'));
// '(555) 123-4567'

// Sanitize HTML
function sanitizeHtml(str) {
  return str.replace(/<[^>]*>/g, '');
}
console.log('Sanitized:', sanitizeHtml('<p>Hello <b>World</b></p>'));
// 'Hello World'

// Convert links to anchor tags
function linkify(text) {
  return text.replace(
    /(https?:\/\/[\w.-]+(?:\/[\w.-]*)*)/g,
    '<a href="$1">$1</a>'
  );
}
console.log('Linkified:', linkify('Visit https://example.com today'));

/**
 * EXAMPLE 18: RegExp Properties and lastIndex
 */

const regex = /test/g;
const testStr2 = 'test1 test2 test3';

console.log('source:', regex.source); // 'test'
console.log('flags:', regex.flags); // 'g'
console.log('global:', regex.global); // true

// lastIndex with global flag
console.log('Initial lastIndex:', regex.lastIndex); // 0
regex.test(testStr2);
console.log('After 1st test:', regex.lastIndex); // 4
regex.test(testStr2);
console.log('After 2nd test:', regex.lastIndex); // 10

// Reset lastIndex
regex.lastIndex = 0;

console.log('\nRegular expressions examples completed!');
Examples - JavaScript Tutorial | DeepML