Docs/JavaScript/Regular Expressions

Regular Expressions

Syntax

/pattern/flags

Methods

  • .test(str) — return true/false
  • .match(regex) — return matches
  • .replace(regex, replacement)

Flags

  • g — global (semua match)
  • i — case insensitive

Patterns Umum

  • \d digit, \w word, \s whitespace
  • + satu/lebih, * nol/lebih, ? opsional
  • [abc] karakter class, ^ awal, $ akhir
script.js
Try It →
const email = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
const phone = /^08\d{8,12}$/;

const o = document.getElementById('output');
o.innerHTML = 
  '// Test
'+
  'email: test@mail.com → '+email.test("test@mail.com")+'
'+
  'email: invalid → '+email.test("invalid")+'
'+
  'phone: 081234567890 → '+phone.test("081234567890")+'
'+
  'phone: 12345 → '+phone.test("12345")+'

'+
  '// Match
'+
  '"I have 3 cats and 2 dogs".match(/\\d+/g)
→ '+JSON.stringify("I have 3 cats and 2 dogs".match(/\d+/g))+'

'+
  '// Replace
'+
  '"Hello World".replace(/o/g, "0")
→ '+"Hello World".replace(/o/g, "0");