在客户搜索页渲染这段生成代码返回的 HTML 前,对格式化函数进行审查。
清理客户姓名,最多保留 12 个可见符号,高亮字面查询,按指定区域排序,并返回安全 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("");
}
生成代码仅作示例,不代表任何特定模型