1. Validating Email Fields
You receive a JSON payload with an email field and need to check if it looks valid before saving it. The RFC 5322 email spec is absurdly complex, but this pattern catches 99% of real-world email addresses while rejecting obvious garbage.
Pattern:
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/What it matches: One or more alphanumeric characters (plus dots, underscores, percent, plus, hyphen) before the @, followed by a domain with at least one dot and a TLD of two or more letters.
Usage:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
function validateUserPayload(json: string): boolean {
const data = JSON.parse(json);
if (!emailRegex.test(data.email)) {
console.error(`Invalid email: ${data.email}`);
return false;
}
return true;
}
// Tests
emailRegex.test("alice@example.com"); // true
emailRegex.test("bob+work@company.co.uk"); // true
emailRegex.test("not-an-email"); // false
emailRegex.test("@missing-local.com"); // false
emailRegex.test("missing@.com"); // falseThis is not meant to replace server-side validation or sending a confirmation email. It is a quick client-side check to catch typos before the data leaves the browser.
2. Extracting URLs from JSON String Values
You have a large JSON document (maybe a CMS export or API response) and need to find all URLs buried in string values. This pattern matches HTTP and HTTPS URLs.
Pattern:
/https?:\/\/[^\s"',}\]]+/g
What it matches: Starts with http:// or https://, then captures everything until it hits whitespace, a quote, comma, closing brace, or closing bracket. Those are the characters that typically end a URL inside a JSON value.
Usage:
const urlRegex = /https?:\/\/[^\s"',}\]]+/g;
const jsonStr = JSON.stringify({
profile: {
website: "https://example.com/about",
bio: "Check out https://blog.example.com for more",
avatar: "https://cdn.example.com/img/avatar.png"
},
links: ["http://old-site.com", "https://new-site.com/path?q=1"]
});
const urls = jsonStr.match(urlRegex) || [];
console.log(urls);
// [
// "https://example.com/about",
// "https://blog.example.com",
// "https://cdn.example.com/img/avatar.png",
// "http://old-site.com",
// "https://new-site.com/path?q=1"
// ]3. Finding All Keys Matching a Pattern
You are working with a 5,000-line JSON config file and need to find every key that looks like it might contain a secret (keys named api_key, secret, password, token, etc.). Useful for security audits.
Pattern:
/"([^"]*(?:secret|password|token|api_key|apikey|auth)[^"]*)"\s*:/gi
What it matches: Any JSON key (quoted string followed by a colon) that contains the words secret, password, token, api_key, apikey, or auth anywhere in the key name. Case-insensitive.
Usage:
const secretKeyRegex =
/"([^"]*(?:secret|password|token|api_key|apikey|auth)[^"]*)"\s*:/gi;
const configJson = `{
"database_url": "postgres://localhost/mydb",
"api_key": "sk_live_abc123",
"jwt_secret": "super-secret-value",
"app_name": "MyApp",
"auth_token": "bearer_xyz",
"smtp_password": "mail123",
"debug": true
}`;
const matches = [...configJson.matchAll(secretKeyRegex)];
const sensitiveKeys = matches.map(m => m[1]);
console.log(sensitiveKeys);
// ["api_key", "jwt_secret", "auth_token", "smtp_password"]Run this against your config files, environment exports, or API responses before committing or logging them. It is a simple way to catch accidental secret exposure.
4. Removing Trailing Commas from Malformed JSON
You pasted JSON from a JavaScript file, a config file, or a log output, and it has trailing commas. JSON.parse rejects trailing commas, but this regex can strip them.
Pattern:
,\s*([}\]])
What it matches: A comma followed by optional whitespace, then a closing brace or bracket. The capture group grabs the closing character so the replacement can keep it.
Usage:
function fixTrailingCommas(malformedJson: string): string {
return malformedJson.replace(/,\s*([}\]])/g, "$1");
}
const bad = `{
"name": "Alice",
"tags": ["admin", "user",],
"active": true,
}`;
// JSON.parse(bad) throws SyntaxError
const fixed = fixTrailingCommas(bad);
console.log(JSON.parse(fixed));
// { name: "Alice", tags: ["admin", "user"], active: true }Caveat: this is a quick fix, not a proper parser. It will break if your JSON string values contain commas followed by braces. For a robust solution, use a lenient JSON parser like json5. But for quick cleanup of config files and log output, this regex does the job.
5. Replacing Single Quotes with Double Quotes
Another common malformed-JSON problem: data that uses single quotes instead of double quotes. This happens when someone copies a Python dictionary or a JavaScript object literal and expects it to be valid JSON.
Pattern:
/'/g
The naive approach (replace all single quotes with double quotes) works for simple cases, but breaks when values contain apostrophes. A safer approach:
Safer replacement:
function singleToDoubleQuotes(input: string): string {
// Match single-quoted strings, handling escaped single quotes
return input.replace(
/'([^'\\]*(?:\\.[^'\\]*)*)'/g,
(_, content) => {
// Escape any unescaped double quotes inside the value
const escaped = content.replace(/"/g, '\\"');
// Unescape single quotes (they don't need escaping in double-quoted strings)
const unescaped = escaped.replace(/\\'/g, "'");
return `"${unescaped}"`;
}
);
}
const pythonDict = "{'name': 'O\\'Brien', 'age': 30}";
const jsonStr = singleToDoubleQuotes(pythonDict);
console.log(jsonStr);
// {"name": "O'Brien", "age": 30}
console.log(JSON.parse(jsonStr));
// { name: "O'Brien", age: 30 }6. Matching ISO 8601 Date Strings
JSON has no native date type, so dates are stored as strings. When processing a JSON document, you might need to find all values that look like ISO 8601 dates (the most common format in APIs).
Pattern:
/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})/gWhat it matches: A date in the format YYYY-MM-DDThh:mm:ss, optionally followed by fractional seconds, ending with Z (UTC) or a timezone offset like +05:30.
Usage: find and convert all date strings in a JSON object:
const isoDateRegex =
/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})/g;
// Use a JSON reviver to auto-convert date strings to Date objects
function parseWithDates(jsonStr: string): unknown {
return JSON.parse(jsonStr, (_key, value) => {
if (typeof value === "string" && isoDateRegex.test(value)) {
// Reset lastIndex since we used the g flag
isoDateRegex.lastIndex = 0;
const date = new Date(value);
if (!isNaN(date.getTime())) {
return date;
}
}
return value;
});
}
const data = parseWithDates(`{
"user": "Alice",
"createdAt": "2025-03-10T14:30:00Z",
"lastLogin": "2025-03-10T09:15:00.000+05:30",
"bio": "Not a date: 2025-03-10"
}`);
console.log(data);
// {
// user: "Alice",
// createdAt: Date(2025-03-10T14:30:00.000Z),
// lastLogin: Date(2025-03-10T03:45:00.000Z),
// bio: "Not a date: 2025-03-10" <-- not converted (no time component)
// }Notice the isoDateRegex.lastIndex = 0 reset. When you use the g flag, the regex object remembers where it last matched. If you call .test() in a loop without resetting, it will alternate between true and false. This is one of JavaScript's worst regex gotchas.