Review a generated name list

from String methods
Node 24 advanced 7 min 4 issues to find

Review this generated formatter before its HTML is rendered in a customer-search page.

Trim customer names, keep at most 12 visible symbols, highlight a literal query, sort for the chosen locale, and return safe HTML.

JavaScript
function buildNameMatches(names, query, locale) {
  const output = [];
  for (const rawName of names) {
    const segmenter = new Intl.Segmenter(locale, { granularity: "grapheme" });
    const name = rawName.trim();
    const parts = [...segmenter.segment(name)].map(({ segment }) => segment);
    const shortened = parts.length > 12 ? `${parts.slice(0, 12).join("")}…` : name;
    const highlighted = shortened.replaceAll(
      query,
      () => `<mark>${query}</mark>`,
    );
    output.push(`<li>${highlighted}</li>`);
  }
  output.sort((a, b) => a.localeCompare(b, locale) === -1);
  return output.join("");
}

generated code is illustrative, not from any one model

Open in playground
Report an error