JavaScript/Examples
[i]Learn· Regular expressions

Examples

Note: Several examples are also available in:

Using special characters to verify input

In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid.

The regular expression looks for:

  1. the beginning of the line of data: ^
  2. followed by three numeric characters \d{3} OR | a left parenthesis \(, followed by three digits \d{3}, followed by a close parenthesis \), in a non-capturing group (?:)
  3. followed by one dash, forward slash, or decimal point in a capturing group ()
  4. followed by three digits \d{3}
  5. followed by the match remembered in the (first) captured group \1
  6. followed by four digits \d{4}
  7. followed by the end of the line of data: $

HTML

<p>
  Enter your phone number (with area code) and then click "Check".
  <br />
  The expected format is like ###-###-####.
</p>
<form id="form">
  <input id="phone" />
  <button type="submit">Check</button>
</form>
<p id="output"></p>

JavaScript

const form = document.querySelector("#form");
const input = document.querySelector("#phone");
const output = document.querySelector("#output");

const re = /^(?:\d{3}|\(\d{3}\))([-/.])\d{3}\1\d{4}$/;

function testInfo(phoneInput) {
  const ok = re.exec(phoneInput.value);

  output.textContent = ok
    ? `Thanks, your phone number is ${ok[0]}`
    : `${phoneInput.value} isn't a phone number with area code!`;
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  testInfo(input);
});

Tools

RegExr

An online tool to learn, build, & test Regular Expressions.

Regex tester

An online regex builder/debugger

Regex interactive tutorial

An online interactive tutorials, Cheat sheet, & Playground.

Regex visualizer

An online visual regex tester.

Source: Regular expressions by Mozilla Contributors, licensed under CC-BY-SA-2.5. Retrieved 2026-11-18. Changes: Extracted the section "Examples"; added the short section after it ("Tools"); removed the code-block language labels, the live-sample frames, the headings left empty and the previous/next links; moved headings up one level; made links absolute.