[i]Learn· Regular expressions
Examples
Note: Several examples are also available in:
- The reference pages for
exec(),test(),match(),matchAll(),search(),replace(),split() - The guide articles: character classes, assertions, groups and backreferences, quantifiers
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:
- the beginning of the line of data:
^ - 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(?:) - followed by one dash, forward slash, or decimal point in a capturing group
() - followed by three digits
\d{3} - followed by the match remembered in the (first) captured group
\1 - followed by four digits
\d{4} - 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.
scratch
[>_]Terminal
Output appears here when you press Run.
$ ▌