Startup Research v0.1.2 · generic
Archive SHA-256 aa404e349023f320330a8889362b691979723efc3469e48657fc958e624955bb · 36.2 KB · built Nov 27, 2026
src/text.js
// Text helpers for startup-research: normalisation, sentence splitting, safe Markdown, matching.
export const clean = (s) =>
String(s ?? "")
.normalize("NFC")
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200b\u202a-\u202e\u2066-\u2069]/g, " ");
/** Lowercased, whitespace-collapsed, typographic quotes/dashes folded: used to verify quotes. */
export const fold = (s) =>
clean(s)
.toLowerCase()
.replace(/[\u2018\u2019\u201a\u2032]/g, "'")
.replace(/[\u201c\u201d\u201e\u2033]/g, '"')
.replace(/[\u2010-\u2015]/g, "-")
.replace(/\u00a0/g, " ")
.replace(/\s+/g, " ")
.trim();
export function sentences(text) {
const out = [];
for (const para of clean(text).split(/\r?\n/)) {
const p = para.replace(/\s+/g, " ").trim();
if (!p) continue;
for (const s of p.split(/(?<=[.!?])\s+(?=["'(\[]?[\p{Lu}\p{N}])/u)) if (s.trim()) out.push(s.trim().slice(0, 2000));
}
return out;
}
export const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/** Regex matching any of `terms` as whole words (a boundary is only required where the term starts/ends with a letter or digit). */
export function termsRe(terms, flags = "giu") {
const parts = terms
.filter((t) => t && t.trim())
.map((t) => {
const tt = t.trim();
const pre = /^[\p{L}\p{N}]/u.test(tt) ? "(?<![\\p{L}\\p{N}])" : "";
const post = /[\p{L}\p{N}]$/u.test(tt) ? "(?![\\p{L}\\p{N}])" : "";
return `${pre}${escapeRe(tt)}${post}`;
});
return parts.length ? new RegExp(parts.join("|"), flags) : null;
}
/** Markdown escaping for untrusted text: HTML-significant characters as entities, syntax backslash-escaped. */
export const md = (s) =>
clean(s)
.replace(/\s+/g, " ")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/[\\`*_{}[\]|#!~]/g, (c) => `\\${c}`)
.trim();
/** A window of at most `max` characters of `sentence` around position `at`, with ellipses where trimmed. */
export function window(sentence, at, max) {
if (sentence.length <= max) return sentence;
let start = Math.max(0, Math.min(at - Math.floor(max / 3), sentence.length - max));
let end = Math.min(sentence.length, start + max);
const sp = sentence.lastIndexOf(" ", start);
if (start > 0 && sp >= 0 && start - sp < 20) start = sp + 1;
const ep = sentence.indexOf(" ", end);
if (end < sentence.length && ep >= 0 && ep - end < 20) end = ep;
return `${start > 0 ? "\u2026" : ""}${sentence.slice(start, end).trim()}${end < sentence.length ? "\u2026" : ""}`;
}
export const hostOf = (u) => {
try {
return new URL(u).hostname.toLowerCase();
} catch {
return "";
}
};