JavaScript Regular Expressions – A Comprehensive Guide
12 April 2025 | Category: JavaScript
Regular expressions (or regex) in JavaScript are powerful tools used to search, match, and manipulate strings based on specific patterns. Whether you’re validating input, searching through data, or replacing content, regular expressions offer a concise and efficient solution.
1. What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. In JavaScript, it can be created in two ways:
Using regex literals:
let pattern = /abc/;
Using the RegExp
constructor:
let pattern = new RegExp("abc");
2. Basic Syntax
Special Characters:
.
: Matches any single character except newline^
: Matches the beginning of the string$
: Matches the end of the string*
: Matches 0 or more occurrences+
: Matches 1 or more occurrences?
: Matches 0 or 1 occurrence\
: Escapes special characters
Character Classes:
[abc]
: Matches any one of the characters a, b, or c[^abc]
: Matches any character except a, b, or c[a-z]
: Matches any lowercase letter[A-Z]
: Matches any uppercase letter[0-9]
: Matches any digit
Predefined Character Classes:
\d
: Any digit (equivalent to [0-9])\D
: Any non-digit\w
: Any word character (letters, digits, underscore)\W
: Any non-word character\s
: Any whitespace character\S
: Any non-whitespace character
3. Quantifiers
{n}
: Matches exactly n occurrences{n,}
: Matches n or more occurrences{n,m}
: Matches between n and m occurrences
Example:
let regex = /a{2,4}/;
console.log("caaat".match(regex)); // Matches 'aaa'
4. Anchors and Boundaries
^
: Start of string$
: End of string\b
: Word boundary\B
: Non-word boundary
Example:
let regex = /\bis\b/;
console.log("This is a test".match(regex)); // Matches 'is'
5. Groups and Alternation
(abc)
: Capturing group(?:abc)
: Non-capturing group(a|b)
: Matches either a or b
Example:
let regex = /(dog|cat)s?/;
console.log("I love dogs".match(regex)); // Matches 'dogs'
6. Regex Methods in JavaScript
test()
Checks if the pattern exists in a string.
let regex = /hello/;
console.log(regex.test("hello world")); // true
exec()
Returns matched content as an array or null.
let result = /\d+/.exec("Year: 2025");
console.log(result[0]); // 2025
String Methods:
match()
– Finds matchesreplace()
– Replaces matched contentsearch()
– Returns the index of the matchsplit()
– Splits the string using a pattern
Example:
let str = "apple, banana, cherry";
console.log(str.split(/,\s*/)); // ["apple", "banana", "cherry"]
7. Flags in Regex
g
: Global search (all matches)i
: Case-insensitive searchm
: Multi-line search
Example:
let regex = /hello/gi;
let text = "Hello world! hello again!";
console.log(text.match(regex)); // ['Hello', 'hello']
8. Practical Use Cases
a. Email Validation
let emailRegex = /^[\w.-]+@[\w.-]+\.\w+$/;
console.log(emailRegex.test("user@example.com")); // true
b. Password Strength
let passwordRegex = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$/;
// Minimum 8 characters, 1 uppercase letter, 1 digit
c. Extract Numbers
let text = "The price is 250 dollars";
let number = text.match(/\d+/);
console.log(number[0]); // 250
9. Tips and Best Practices
- Always escape special characters properly.
- Test your regex using online tools like regex101.com.
- Use comments and whitespace with the
x
flag in other languages (not available in JavaScript). - Break complex expressions into parts or use helper functions for readability.
10. Conclusion
JavaScript regular expressions are powerful and flexible for string manipulation and pattern matching. Mastering regex takes practice, but it greatly enhances your ability to work with text data. Whether validating form input, parsing data, or performing advanced search and replace, regular expressions are a vital tool in any developer’s toolkit.