Skillversitas

Regular Expressions (Regex) in JavaScript

Regular Expressions (regex) are text search patterns used for flexible validation, searching, and string manipulation. In JavaScript, regex is very useful for validating campus input such as email addresses, student IDs (StudentID), phone numbers, and other data formats.


Creating a Regex

// Two ways to create a regex
const pattern1 = /abc/;              // literal — no escaping needed
const pattern2 = new RegExp("abc");  // constructor — use escaping

// Flags
const global = /hello/gi;  // g: global (all matches), i: case-insensitive

Code Example: Basic Patterns

// === BASIC CHARACTERS ===

// . — any character except newline
/console.log(/a.b/.test("acb"));   // true
console.log(/a.b/.test("ab"));     // false (needs 1 character in the middle)

// \d — digit (0-9)
console.log(/\d/.test("5"));       // true
console.log(/\d/.test("a"));       // false

// \w — word character (a-z, A-Z, 0-9, _)
console.log(/\w/.test("hello"));   // true

// \s — whitespace (space, tab, newline)
console.log(/\s/.test(" "));       // true

// \b — word boundary
console.log(/\bcode\b/.test("write code here"));  // true
console.log(/\bcode\b/.test("encode"));            // false

// === QUANTIFIERS ===

// * — 0 or more
console.log(/ab*/.test("a"));       // true
console.log(/ab*/.test("abbb"));    // true

// + — 1 or more
console.log(/ab+/.test("a"));       // false
console.log(/ab+/.test("ab"));      // true

// ? — 0 or 1 (optional)
console.log(/colou?r/.test("color"));   // true
console.log(/colou?r/.test("colour"));  // true

// {n} — exactly n times
console.log(/\d{3}/.test("123"));    // true
console.log(/\d{3}/.test("12"));     // false

// {n,m} — between n and m times
console.log(/\d{2,4}/.test("12345")); // true (matches "1234")

// === ANCHORS ===

// ^ — start of string
console.log(/^Hello/.test("Hello World"));  // true
console.log(/^Hello/.test("World Hello"));  // false

// $ — end of string
console.log(/world$/.test("Hello world"));  // true
console.log(/world$/.test("world Hello"));  // false

Character Classes and Groups

// [abc] — one of a, b, or c
console.log(/[aeiou]/.test("hello"));   // true (has 'e')

// [a-z] — character range
console.log(/[a-z]/.test("H"));        // false (uppercase letter)
console.log(/[a-zA-Z]/.test("H"));     // true

// [^abc] — negation (not a, b, or c)
console.log(/[^0-9]/.test("abc"));     // true (has a letter)
console.log(/[^0-9]/.test("123"));     // false (all digits)

// === GROUPS ===

// (abc) — capture group
const match = "John Smith".match(/(\w+) (\w+)/);
console.log(match[1]); // "John"
console.log(match[2]); // "Smith"

// (?:abc) — non-capturing group
const email = "[email protected]";
const domain = email.match(/@(?:university|univ)\.(ac\.id)/);
console.log(domain[0]); // "@university.edu"

// | — OR
console.log(/SI|IF|TI/.test("SI"));    // true
console.log(/SI|IF|TI/.test("TK"));    // false

Lookahead and Lookbehind

// Positive Lookahead (?=...) — something is present AFTER
// Password must contain a digit
console.log(/(?=.*\d)/.test("pass1word")); // true
console.log(/(?=.*\d)/.test("password"));   // false

// Negative Lookahead (?!...) — something is NOT present AFTER
console.log(/^(?!.*admin)/.test("user123"));  // true
console.log(/^(?!.*admin)/.test("admin123")); // false

// Positive Lookbehind (?<=...) — something is present BEFORE
console.log(/(?<=StudentID:)\d{7}/.test("StudentID:2023001")); // true

// Negative Lookbehind (?<!...) — something is NOT present BEFORE
console.log(/(?<!\$)\d+/.test("price100"));  // true
console.log(/(?<!\$)\d+/.test("$100"));      // false (100 is behind $)

Flags

// g — global: all matches, not just the first
const text = "university university university";
console.log(text.match(/university/));     // ["university"] (only the first)
console.log(text.match(/university/g));    // ["university", "university", "university"]

// i — case insensitive
console.log(/hello/i.test("Hello"));   // true
console.log(/hello/i.test("HELLO"));   // true

// m — multiline (^ and $ per line)
const multiline = "line1\nline2";
console.log(/^line2/m.test(multiline)); // true

// s — dotall (. also matches newline)
console.log(/a.b/s.test("a\nb"));  // true

String Methods with Regex

const email = "Contact me at [email protected] or [email protected]";

// test — check for a match (returns a boolean)
console.log(/@university\.edu/.test(email)); // true

// match — retrieve matches (returns an array)
const allEmails = email.match(/[\w.]+@[\w.]+/g);
console.log(allEmails); // ["[email protected]", "[email protected]"]

// replace — replace matches
const result = email.replace(/@[\w.]+/g, "@[REDACTED]");
console.log(result); // "Contact me at john@[REDACTED] or anna@[REDACTED]"

// search — index of the first match (returns a number)
console.log(email.search(/anna/)); // 38

// split — split a string based on a pattern
const fullName = "John Smith";
const words = fullName.split(/\s+/);
console.log(words); // ["John", "Smith"]

Code Explanation

Method Return Purpose
regex.test(string) Boolean Check whether the pattern matches
string.match(regex) Array/null Retrieve all matches
string.replace(regex, replacement) New String Replace matches
string.search(regex) Number Index of the first match
string.split(regex) Array Split the string

Important tips:
- Always escape special characters: ., +, *, ?, (, ), [, ], {, }, ^, $, \ → put a \ in front of them.
- Use \b (word boundary) for exact word searches — it avoids partial matches.


Everyday Case Studies

1. Campus Email Validation

function validateUniversityEmail(email) {
  // General email pattern + campus domain
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailPattern.test(email);
}

// Valid email
console.log(validateUniversityEmail("[email protected]"));    // true
console.log(validateUniversityEmail("[email protected]"));        // true

// Invalid email
console.log(validateUniversityEmail("john@"));                 // false
console.log(validateUniversityEmail("@university.edu"));         // false
console.log(validateUniversityEmail("john.university.edu"));     // false

2. StudentID Format Validation

function validationStudentID(studentId) {
  // StudentID format: 2023 + 3-digit majorCode + 3 sequential digits = 8 digits
  const studentIdPattern = /^20\d{2}\d{3}\d{3}$/;
  return {
    valid: studentIdPattern.test(studentId),
    format: studentIdPattern.test(studentId) ? "Valid" : "Format: 2023PPPUUU (8 digit)"
  };
}

console.log(validationStudentID("2023001001"));  // { valid: true, format: "Valid" }
console.log(validationStudentID("2023001"));     // { valid: false, format: "Format: ..." }
console.log(validationStudentID("23abc001"));    // { valid: false, format: "Format: ..." }

3. Validating and Formatting Phone Numbers

function formatPhoneNumber(input) {
  // Remove all non-digit characters
  let cleaned = input.replace(/\D/g, "");

  // Handle 08xx → +628xx format
  if (cleaned.startsWith("08")) {
    cleaned = "62" + cleaned.substring(1);
  }

  // Validate the Indonesian format
  const indonesiaPattern = /^62[8][0-9]{8,11}$/;
  const valid = indonesiaPattern.test(cleaned);

  return {
    original: input,
    cleaned: cleaned,
    formatted: valid ? `+${cleaned.substring(0, 2)} ${cleaned.substring(2, 6)}-${cleaned.substring(6)}` : null,
    valid
  };
}

console.log(formatPhoneNumber("0812-3456-7890"));
// { original: "0812-3456-7890", cleaned: "6281234567890", formatted: "+62 8123-4567-890", valid: true }

console.log(formatPhoneNumber("08123456"));
// { ..., valid: false } (too short)

4. Extracting Data from Text

const studentText = `
  Name: John Smith
  StudentID: 2023001
  Email: [email protected]
  GPA: 3.75
  No. HP: 081234567890
`;

function extractData(text) {
  const data = {};

  const nameMatch = text.match(/Name:\s*(.+)/);
  if (nameMatch) data.name = nameMatch[1].trim();

  const studentIdMatch = text.match(/StudentID:\s*(\d+)/);
  if (studentIdMatch) data.studentId = studentIdMatch[1];

  const emailMatch = text.match(/Email:\s*([\w.+-]+@[\w.-]+)/);
  if (emailMatch) data.email = emailMatch[1];

  const ipkMatch = text.match(/GPA:\s*([\d.]+)/);
  if (ipkMatch) data.gpa = parseFloat(ipkMatch[1]);

  const hpMatch = text.match(/No\. HP:\s*([\d-]+)/);
  if (hpMatch) data.phoneNumber = hpMatch[1].replace(/-/g, "");

  return data;
}

console.log(extractData(studentText));
// { name: "John Smith", studentId: "2023001", email: "[email protected]", gpa: 3.75, phoneNumber: "081234567890" }

Conclusion

  • Regex in JavaScript is created with the literal /pattern/ or new RegExp("pattern").
  • Quantifiers (*, +, ?, {n,m}) control how many times characters repeat.
  • Anchors (^, $) restrict the search to the start/end of a string.
  • Groups () for capturing specific parts of a match.
  • Lookahead/Lookbehind for conditions without capturing characters.
  • Flags: g (global), i (case-insensitive), m (multiline).
  • Main methods: test(), match(), replace(), search(), split().
  • Extremely useful for input validation (email, StudentID, phone) and data extraction from raw text.