Regular expressions are useful for input validation, text extraction, log analysis, and everyday JavaScript development. But copying a regex from the internet without understanding its limitations can create unexpected bugs.
This guide brings together 30 practical JavaScript regex patterns, explains what they do, and shows how to test them.
You can also explore the open-source DevToolkit Regex Pattern Library, which contains 32 documented patterns, or experiment with the free online Regex Tester.
1. Input validation patterns
1. Email address
const regex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
regex.test("dev@example.com"); // true
regex.test("dev@example"); // false
Useful for basic email formatting checks. It is not a complete email validator and cannot confirm whether an email address exists.
2. HTTP or HTTPS URL
const regex = /^https?:\/\/[^\s]+$/i;
regex.test("https://example.com/docs"); // true
regex.test("example.com/docs"); // false
Checks for an HTTP or HTTPS prefix followed by non-whitespace characters. Use JavaScript's URL class for more comprehensive URL parsing.
3. Hexadecimal color
const regex = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
regex.test("#3B82F6"); // true
regex.test("3B82F6"); // false
Supports three- and six-digit hexadecimal colors, but not eight-digit colors with alpha channels.
4. Lowercase URL slug
const regex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
regex.test("javascript-regex-guide"); // true
regex.test("JavaScript Regex Guide"); // false
Useful for validating lowercase URL slugs without spaces or repeated hyphens.
5. Alphanumeric string
const regex = /^[A-Za-z0-9]+$/;
regex.test("Developer2026"); // true
regex.test("Developer_2026"); // false
Accepts ASCII letters and digits only. Unicode letters are excluded.
6. Signed integer
const regex = /^[+-]?\d+$/;
regex.test("-42"); // true
regex.test("3.14"); // false
Checks integer syntax but does not enforce a numeric range.
7. Decimal number
const regex = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
regex.test("-12.50"); // true
regex.test(".75"); // true
regex.test("12,50"); // false
Useful for decimal input formats. It does not support scientific notation or locale-specific separators.
8. US ZIP code
const regex = /^\d{5}(?:-\d{4})?$/;
regex.test("94105"); // true
regex.test("94105-1234"); // true
regex.test("9410"); // false
Checks ZIP code format, not whether the postal code actually exists.
2. Networking patterns
9. IPv4 address
const regex = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
regex.test("192.168.1.10"); // true
regex.test("192.168.1.300"); // false
Validates four decimal octets between 0 and 255. It does not identify reserved or private addresses.
10. Basic IPv6 address
const regex = /^(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/;
regex.test("2001:0db8:0000:0000:0000:ff00:0042:8329"); // true
regex.test("2001:db8::1"); // false
This pattern intentionally handles only fully expanded IPv6 addresses. Compressed IPv6 notation requires a more complete validator.
11. MAC address
const regex = /^(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/;
regex.test("00:1A:2B:3C:4D:5E"); // true
regex.test("00:1A:2B:3C:4D"); // false
Checks a common MAC address layout. It does not confirm that the address belongs to a real device.
12. Hostname
const regex = /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
regex.test("api.example.com"); // true
regex.test("-api.example.com"); // false
Checks ASCII hostname labels, but does not perform a DNS lookup.
13. TCP/UDP port number
const regex = /^(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
regex.test("443"); // true
regex.test("65535"); // true
regex.test("70000"); // false
Accepts decimal integers from 0 through 65535. It does not check whether a port is available.
3. Dates, times, and identifiers
14. UUID version 4
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
regex.test("550e8400-e29b-41d4-a716-446655440000"); // true
regex.test("550e8400-e29b-11d4-a716-446655440000"); // false
This checks the UUID layout, version and variant bits. It cannot prove uniqueness.
15. ISO-style calendar date
const regex = /^\d{4}-\d{2}-\d{2}$/;
regex.test("2026-10-11"); // true
regex.test("11/10/2026"); // false
Important: 2026-99-99 also matches because the expression checks the format, not calendar validity.
16. 24-hour time
const regex = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
regex.test("23:45"); // true
regex.test("24:00"); // false
Validates time in HH:MM format without seconds or time zones.
17. ISO-style date-time with timezone
const regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
regex.test("2026-10-11T14:30:00Z"); // true
regex.test("2026/10/11 14:30:00"); // false
Checks the expected string structure. It does not verify valid calendar dates or timezone offsets.
18. Simple duration
const regex = /^(?:\d+(?:\.\d+)?)(?:ms|s|m|h|d)$/i;
regex.test("250ms"); // true
regex.test("2.5h"); // true
regex.test("two hours"); // false
Useful for configuration inputs such as timeout values. Compound durations like 1h30m are not supported.
4. Text processing patterns
19. Whitespace runs
const regex = /\s+/g;
"Hello World\nAgain".match(regex);
// [" ", "\n"]
Matches one or more whitespace characters.
20. Duplicate spaces
const regex = / {2,}/g;
"Hello World".replace(regex, " ");
// "Hello World"
Targets consecutive literal spaces. Tabs and newlines are not included.
21. HTML-like tags
const regex = /<\/?[A-Za-z][^>]*>/g;
"<p>Hello</p>".match(regex);
// ["<p>", "</p>"]
Useful for demonstrating text pattern matching, but not suitable for parsing arbitrary HTML. For actual HTML documents, use an HTML parser or DOM APIs.
22. Double-quoted strings
const regex = /"(?:\\.|[^"\\])*"/g;
const input = 'name="DevToolkit"';
input.match(regex);
// ['"DevToolkit"']
Handles common escaped characters inside double-quoted strings, but is not a complete programming-language lexer.
23. Quoted CSV field
const regex = /^"(?:""|[^"])*"$/;
regex.test('"Hello, world"'); // true
regex.test('"Unterminated'); // false
Checks one quoted CSV field. Parsing an entire CSV document requires additional handling.
5. Developer and programming patterns
24. JavaScript-style identifier
const regex = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
regex.test("user_$1"); // true
regex.test("1stUser"); // false
This covers common ASCII identifier syntax but not reserved keywords or all Unicode identifier rules.
25. Common log level
const regex = /\b(?:TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b/gi;
"2026-10-11 ERROR Request failed".match(regex);
// ["ERROR"]
Useful for detecting common log severity labels.
26. Semantic version string
const regex = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
regex.test("1.4.0"); // true
regex.test("v1.4.0-beta.2"); // true
regex.test("1.4"); // false
Useful for broad version-format checks. It does not enforce every rule of the SemVer 2.0 specification.
27. Base64 string
const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
regex.test("SGVsbG8="); // true
regex.test("SGVsbG8!"); // false
Checks the standard padded Base64 character structure but does not decode the input.
28. Hexadecimal number
const regex = /^(?:0x)?[0-9A-Fa-f]+$/i;
regex.test("0xFF00AA"); // true
regex.test("0xGHI"); // false
Accepts hexadecimal digits with an optional 0x prefix.
29. Absolute Unix-style path
const regex = /^\/(?:[^\0\n\/]+\/)*[^\0\n\/]*$/;
regex.test("/var/log/app.log"); // true
regex.test("var/log/app.log"); // false
Checks that a string starts with / and follows a simple Unix-style path structure. It does not check whether the path exists or is safe to access.
30. JSON string token
const regex = /"(?:\\(?:["\\\/bfnrt]|u[0-9A-Fa-f]{4})|[^"\\\u0000-\u001F])*"/;
regex.test('"hello"'); // true
regex.test('"line\\nvalue"'); // true
Matches a JSON-style string token. It does not validate an entire JSON document.
Use JSON.parse() for complete JSON validation instead.
How to test regex patterns in JavaScript
JavaScript includes the built-in RegExp object.
You can compile a regular expression, run it against input, and examine the results.
function testPattern(pattern, input, flags = "") {
try {
const regex = new RegExp(pattern, flags);
return {
valid: true,
matches: regex.test(input)
};
} catch (error) {
return {
valid: false,
error: error.message
};
}
}
console.log(
testPattern("^\\d+$", "12345")
);
Expected result:
{
valid: true,
matches: true
}
For repeated calls, remember that regex objects using the g or y flag are stateful: test() can update lastIndex. Reset it or create a new RegExp instance when appropriate.
Common regex mistakes
1. Forgetting string boundaries
Compare:
/\d+/.test("abc123xyz"); // true
/^\d+$/.test("abc123xyz"); // false
The ^ and $ anchors help restrict what the expression accepts.
2. Confusing syntax validation with real validation
A regex might match a date-shaped string without proving the date exists.
Similarly, matching an email address doesn't prove the mailbox exists.
3. Using regular expressions to parse structured documents
Avoid using a single regex to parse entire HTML, JSON, or complex programming languages.
Purpose-built parsers are generally more reliable.
4. Ignoring regex performance
Poorly designed regular expressions can cause excessive backtracking on certain inputs.
Be cautious with ambiguous nested repetitions, long untrusted input, and expressions running inside performance-sensitive code.
5. Forgetting the difference between flags
Common JavaScript regex flags include:
| Flag | Meaning |
|---|---|
g |
Global matching |
i |
Case-insensitive matching |
m |
Multiline anchors |
s |
Dot matches line terminators |
u |
Unicode-aware matching |
y |
Sticky matching |
d |
Match indices |
Flag support and behavior should be verified against your target JavaScript runtime.
Test these expressions interactively
Reading a regex is useful, but testing positive examples, negative examples, and edge cases is more effective.
I maintain DevToolkit, a collection of free browser-based developer utilities.
The DevToolkit Regex Tester includes:
- A searchable library of 32 regex patterns.
- Matching and non-matching examples.
- Explanations and limitations.
- JavaScript regex flag support.
- Match highlighting and replacement testing.
- Client-side processing.
The patterns are also available in the public DevToolkit Regex Pattern Library on GitHub.
The open-source repository provides pattern data, automated tests, documentation, and contribution guidelines.
If you find an incorrect pattern, missing edge case, or useful addition, contributions and issue reports are welcome.
Final thoughts
The most useful regex isn't necessarily the shortest or most complicated one. It is the expression that handles the intended inputs correctly, has clearly documented limitations, and can be maintained by another developer.
Whenever you adopt a regex:
- Understand what it actually matches.
- Test valid and invalid inputs.
- Document its limitations.
- Consider performance and security.
- Prefer a parser when the data structure demands one.
Which regular expression do you find yourself rewriting most often?
Originally prepared for the DEV Community developer audience.
Tags: javascript, regex, webdev, opensource
Top comments (1)
tr.ee/dev-to
Some comments have been hidden by the post's author - find out more