A Regular Expression (RegExp) is a pattern used to match character combinations in strings. In JavaScript, regex is widely used for validation, searching, and replacing text.
You can write regex using the literal form /pattern/flags or with the RegExp constructor. JavaScript then provides methods like test(), exec(), match(), and replace() to work with these patterns.
\d, \w, \s.^) or end ($).+, *, {n,m}).Regex syntax
/pattern/modifiers
// or using RegExp constructor:
new RegExp("pattern", "modifiers")
Basic patterns
/abc/ // Matches "abc"
\d // Matches any digit (0–9)
\w // Matches any word character (a-z, A-Z, 0–9, _)
\s // Matches whitespace
. // Any single character except newline
^abc // Must start with "abc"
abc$ // Must end with "abc"
a|b // Matches "a" or "b"
[abc] // Matches "a", "b", or "c"
[^abc] // Anything except "a", "b", or "c"
[a-z] // Range: a to z
i — Case-insensitive match.g — Global match (find all matches, not just first).m — Multi-line mode (affects ^ and $).
\d // Digits
\D // Non-digits
\w // Word characters
\W // Non-word characters
\s // Whitespace
\S // Non-whitespace
\b // Word boundary
\B // Non-word boundary
. // Any character except newline
+ // One or more
* // Zero or more
? // Zero or one
{n} // Exactly n
{n,} // At least n
{n,m} // Between n and m
let pattern = /hello/i;
console.log(pattern.test("Hello World")); // true
let result = /(\d+)/.exec("Price: 100 dollars");
console.log(result[0]); // "100"
let str = "The rain in Spain";
let matches = str.match(/ain/g);
console.log(matches); // ["ain", "ain"]
let text = "Hello 123!";
let newText = text.replace(/\d+/, "***");
console.log(newText); // "Hello ***!"
/hello/i.test("Hello World") → true because the pattern "hello" matches regardless of case./(\d+)/.exec("Price: 100 dollars") finds the first group of digits, so result[0] is "100"."The rain in Spain".match(/ain/g) → an array of all matches: ["ain", "ain"]."Hello 123!".replace(/\d+/, "***") replaces the digits with "***", giving "Hello ***!".test() when you only need a boolean validation result./pattern/gi for flexible, case-insensitive global matching.replace() with regex for powerful text substitutions.() to group patterns and capture parts of the match.., *, ? when you want them literal (e.g. /\./ for a dot).\d or [0-9] consistently in your codebase.match() with /\d+/g to extract all numbers from a string.replace() to mask a phone number, showing only the last two digits.\b to match whole words (e.g. match "cat" but not "scatter").