// What a typed phrase is searched as (release 34): a regular expression as // written, or plain words made into a tolerant one. // // Plain words are what a person types: "slow news day". A caption writes the // same words "slow, news day" or "slow-news day", and says "days" as often as // "day", so plain words become a pattern that takes any run of spaces, commas, // full stops and hyphens between the words, an apostrophe or none inside one // ("dont" finds "don't" and "don’t"), and an optional plural on the last word. // Whole words only: "news" does not match inside "newsletter". // // Pure and dependency-free, so the phrase finder's page, its server and the // `umtool phrases` CLI all read a phrase the same way. /** The characters that make a typed phrase a regular expression in `auto` mode. */ export const REGEX_CHARS = /[\\^$.|?*+()[\]{}]/; const GAP = String.raw`[\s,.\-]+`; const escape = (s) => s.replace(/[\\^$.|?*+()[\]{}]/g, "\\$&"); /** The words of a plain phrase, lower-cased, apostrophes kept. */ export function phraseWords(text) { return String(text ?? "") .toLowerCase() .replace(/[’‘`]/g, "'") .split(/[\s,.;:!?"“”()\-–—/]+/) .map((w) => w.replace(/^'+|'+$/g, "")) .filter(Boolean); } /** * Plain words → a regular expression's source: `slow news day` → * `\bslow[\s,.\-]+news[\s,.\-]+day(?:s|es)?\b`. Throws on no words. */ export function wordsPhraseSource(text) { const ws = phraseWords(text); if (!ws.length) throw new Error("a phrase is required"); const parts = ws.map((w) => w.split("'").map(escape).join("['’]?")); const last = parts.length - 1; const w = ws[last]; // The plural: story → stories, day → days, box → boxes; a word already // ending in s (news, chess) or in a digit is left as it is. if (/[^aeiou]y$/.test(w) && w.length > 2) parts[last] = parts[last].slice(0, -1) + "(?:y|ies)"; else if (/[a-z]$/.test(w) && !w.endsWith("s")) parts[last] += "(?:s|es)?"; return String.raw`\b` + parts.join(GAP) + String.raw`\b`; } /** * What `text` is searched as. `mode`: `regex` takes it as written, `words` * makes it a tolerant pattern, `auto` (the default) is `regex` when it holds a * regular expression's characters and `words` otherwise. Returns `{ source, * mode }` with the mode used; throws when the text is empty or the expression * does not compile. * * @param {string} text * @param {"auto" | "words" | "regex"} [mode] * @returns {{ source: string, mode: "words" | "regex" }} */ export function phraseSourceOf(text, mode = "auto") { const t = String(text ?? "").trim(); if (!t) throw new Error("a phrase is required"); const used = mode === "regex" || (mode !== "words" && REGEX_CHARS.test(t)) ? "regex" : "words"; const source = used === "regex" ? t : wordsPhraseSource(t); try { new RegExp(source, "gi"); } catch (e) { throw new Error(`not a regular expression: ${e instanceof Error ? e.message : String(e)}`); } return { source, mode: used }; }