JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What are some common regex patterns in JavaScript?

Asked on Aug 30, 2024

Answer

Regular expressions (regex) are powerful tools for pattern matching and text manipulation in JavaScript. Here are some common regex patterns used in JavaScript:
// Match an email address
        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

        // Match a URL
        const urlPattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;

        // Match a date in YYYY-MM-DD format
        const datePattern = /^\d{4}-\d{2}-\d{2}$/;

        // Match a US phone number (e.g., (123) 456-7890)
        const phonePattern = /^\(\d{3}\) \d{3}-\d{4}$/;

        // Match a hexadecimal color code
        const hexColorPattern = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
Additional Comment:
  • These patterns are commonly used for validating inputs.
  • The email pattern checks for a standard email format.
  • The URL pattern matches both HTTP and HTTPS URLs.
  • The date pattern ensures the input is in the "YYYY-MM-DD" format.
  • The phone pattern is specific to the US format with parentheses and dashes.
  • The hex color pattern matches both 3-digit and 6-digit hexadecimal color codes.
✅ Answered with JavaScript best practices.
← Back to All Questions