How do you validate the entire value?
const orderIdPattern = /^ORD-[0-9]{6}$/;
function isOrderId(value) {
return typeof value === "string" && orderIdPattern.test(value);
}
console.log(isOrderId("ORD-012345")); // true
console.log(isOrderId("prefix ORD-012345")); // false
console.log(isOrderId("ORD-012345\n")); // false
console.log(isOrderId(123456)); // false
An order identifier must contain ORD- followed by exactly six ASCII digits. [0-9] is a character class, {6} requires six occurrences, and ^ and $ constrain matching to input boundaries when m is absent. test() returns a boolean. [1][3]
Do not enable m for a whole-value validator: it changes the anchors to line boundaries. Regex literals and new RegExp() use the same pattern syntax, but a normal JavaScript string passed to the constructor needs doubled backslashes, as in new RegExp("\\d+"). [12]
Why does test() alternate between true and false?
const statefulPattern = /\d+/g;
console.log(statefulPattern.test("42")); // true
console.log(statefulPattern.lastIndex); // 2
console.log(statefulPattern.test("42")); // false
console.log(statefulPattern.lastIndex); // 0
const validationPattern = /^\d+$/;
console.log(validationPattern.test("42")); // true
console.log(validationPattern.test("42")); // true
Global and sticky regex objects retain their search position in lastIndex. A second call may start at the end of the previous match rather than at the beginning. On failure, the position resets to zero. [4]
The g flag can search forward from that position; y requires a match at the position itself. Avoid both for independent validation. i ignores case, m changes anchors, and s lets the dot match line terminators. [2]
How do you extract multiple records with named groups?
const log = "ERROR E101: Disk full\nERROR E205: Timeout";
const errorPattern = /^ERROR (?<code>E\d{3}): (?<message>[^\r\n]+)$/gm;
const errors = Array.from(log.matchAll(errorPattern), ({ groups }) => ({
code: groups.code,
message: groups.message,
}));
console.log(errors);
// [
// { code: "E101", message: "Disk full" },
// { code: "E205", message: "Timeout" },
// ]
With g, match() returns complete matches without capture groups. matchAll() instead provides an iterator containing match details; (?<code>...) gives a capture a meaningful name. A RegExp argument must have g. [5][6]
The example parses a defined log format, not arbitrary logs. m enables line-based matching. (?:...) groups a subpattern without capturing it, while \k<name> matches text previously captured under that name. matchAll() clones the regex but starts at its current lastIndex, so use a fresh pattern when starting from the beginning. [5][6]
How do you replace matches without losing data?
const text = "Open ticket #12 and ticket #34.";
const ticketPattern = /#(?<id>[0-9]+)/g;
const result = text.replace(ticketPattern, (match, id) => {
return `TICKET-${id.padStart(5, "0")}`;
});
console.log(result); // Open ticket TICKET-00012 and ticket TICKET-00034.
A replace() callback receives the match and captured substrings and can transform each identifier. Without g, a regex argument to replace() replaces only the first match. [7]
padStart() keeps the identifier as a string, preserving leading zeros. Simple replacements can use $1 or $<id>. If replacement text comes from a user, returning it from a callback prevents sequences such as $& from being interpreted as replacement instructions. [7]
How do you handle Unicode letters and accents?
function extractWords(text) {
const normalizedText = text.normalize("NFC");
return normalizedText.match(/\p{L}[\p{L}\p{M}]*/gu) ?? [];
}
console.log(extractWords("Zażółć 東京 café"));
// ["Zażółć", "東京", "café"]
console.log(extractWords("cafe\u0301")); // ["café"]
console.log(extractWords("123")); // []
\w is not a universal letter class and \d covers ASCII digits. \p{L} matches Unicode letters and \p{M} combining marks; property escapes require u or v, which cannot be combined. NFC normalization makes canonically equivalent spellings consistent when that fits the domain. [8]
The example extracts runs of letters, not validated personal names or linguistically complete words. Unicode-aware matching operates on code points, not entire grapheme clusters. Use Intl.Segmenter when you need language-sensitive word or grapheme segmentation. [13]
How do you safely insert literal user text?
function containsLiteral(text, query) {
if (query.length === 0) {
return false;
}
return text.includes(query);
}
function createLiteralPattern(query) {
if (typeof RegExp.escape !== "function") {
throw new Error("RegExp.escape() requires a supported runtime");
}
return new RegExp(RegExp.escape(query), "gu");
}
console.log(containsLiteral("a.b", "a.b")); // true
console.log(containsLiteral("axb", "a.b")); // false
if (typeof RegExp.escape === "function") {
console.log(createLiteralPattern("a.b").test("axb")); // false
console.log(createLiteralPattern("a.b").test("a.b")); // true
}
Passing a.b directly to a regex constructor makes the dot a metacharacter. Use includes() for plain substring search. When composing a regex, RegExp.escape() encodes input as a literal pattern fragment. [9]
Older runtimes may not support this API. Detect it or use a specification-compliant polyfill rather than an improvised replacement expression. Escaping regex syntax neither sanitizes HTML nor fixes expensive matching in the surrounding pattern.
How do you prevent ReDoS and main-thread stalls?
function isTagList(value) {
if (typeof value !== "string" || value.length > 256) {
return false;
}
const tags = value.split(",");
const tagPattern = /^[a-z0-9]{1,24}$/;
if (tags.length > 10) {
return false;
}
return tags.every((tag) => tagPattern.test(tag));
}
console.log(isTagList("css,javascript")); // true
console.log(isTagList("css,,javascript")); // false
console.log(isTagList("a".repeat(257))); // false
Overlapping quantifiers and ambiguous alternatives can trigger excessive backtracking, particularly on input that almost matches but fails near the end. Input limits help, but cannot substitute for simplifying the pattern. [11]
For a comma-separated tag list, split first and validate each bounded token. The example limits (256 UTF-16 code units, 10 tags and 24 ASCII characters per tag) are product rules, not universal thresholds. Test difficult inputs in an isolated worker or process with a deadline; a timer on the same thread cannot interrupt a synchronous regex.
How do you use regex in HTML forms?
<label for="order-id">Order ID</label>
<input
id="order-id"
name="orderId"
type="text"
pattern="ORD-[0-9]{6}"
required
aria-describedby="order-hint"
/>
<p id="order-hint">Example: ORD-012345</p>Try the patterns in the POLPROG Regex Tester.
The HTML pattern attribute takes a pattern without enclosing slashes and matches the entire nonempty value. Modern HTML compiles it with v, which changes some character-class syntax compared with traditional regex patterns. required separately rejects empty input. [10]
Provide a visible format hint linked to the input. validity.patternMismatch exposes a format error, but browser validation is not a security boundary: repeat validation and business-rule checks on the server.
