如何将省略撇号的用户输入转换为带撇号格式匹配API Slug?
解决搜索栏Slug匹配问题:处理省略撇号的输入
针对你遇到的用户输入省略撇号导致Slug不匹配API的问题,推荐两种更优方案,既避免全量拉取数据,也不用硬编码所有可能输入:
方案一:提前补全常见缩写的撇号,再生成Slug
通过正则识别常见的省略撇号的英文缩写,先还原成带撇号的形式,再生成符合API规则的Slug。
示例代码(JavaScript):
// 定义常见缩写与完整形式的映射 function fixContractions(input) { const contractionMap = new Map([ ["im", "i'm"], ["dont", "don't"], ["cant", "can't"], ["wont", "won't"], ["isnt", "isn't"], ["arent", "aren't"], ["wasnt", "wasn't"], ["werent", "weren't"], ["hasnt", "hasn't"], ["havent", "haven't"], ["hadnt", "hadn't"], ["doesnt", "doesn't"], ["didnt", "didn't"], ["its", "it's"], ["theres", "there's"], ["theyre", "they're"], ["youre", "you're"], ["were", "we're"], ["whos", "who's"] ]); // 匹配单词边界的缩写,替换为带撇号的完整形式 return input.replace(/\b(im|dont|cant|wont|isnt|arent|wasnt|werent|hasnt|havent|hadnt|doesnt|didnt|its|theres|theyre|youre|were|whos)\b/gi, match => { return contractionMap.get(match.toLowerCase()) || match; }); } // 生成Slug:先补全缩写,再做格式转换 function generateSlug(input) { const fixedInput = fixContractions(input); return fixedInput.toLowerCase() .replace(/[^a-z0-9']+/g, '-') // 把非字母数字/撇号的字符换成连字符 .replace(/^-+|-+$/g, ''); // 去除首尾多余的连字符 } // 使用示例 const userInput = "im good"; const slug = generateSlug(userInput); // 得到 "i'm-good",与API的Slug匹配
方案二:生成多版本Slug并行请求,兼容原输入和补全后输入
如果担心有遗漏的缩写,可以同时生成原输入的Slug和补全后的Slug,并行发送请求,只要有一个返回有效结果就使用。这种方式容错性更高,且性能损耗极低。
示例代码(JavaScript):
async function fetchSuggestions(input) { // 生成原输入的Slug const originalSlug = input.toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); // 补全缩写后生成Slug const fixedInput = fixContractions(input); const correctedSlug = fixedInput.toLowerCase() .replace(/[^a-z0-9']+/g, '-') .replace(/^-+|-+$/g, ''); // 准备请求列表,避免重复请求相同Slug const requests = []; requests.push(fetch(`/api/suggestions?slug=${originalSlug}`)); if (originalSlug !== correctedSlug) { requests.push(fetch(`/api/suggestions?slug=${correctedSlug}`)); } try { const responses = await Promise.all(requests); // 遍历响应,返回第一个有有效数据的结果 for (const res of responses) { if (res.ok) { const data = await res.json(); if (data.length > 0) { return data; } } } return []; } catch (err) { console.error('获取建议失败:', err); return []; } }
这两个方案的优势:
- 无需拉取全量API数据,大幅节省服务器资源
- 仅维护常见缩写映射,代码易扩展,比硬编码所有输入优雅得多
- 方案二能兼容用户输入的特殊情况,容错性更强
内容的提问来源于stack exchange,提问作者Giovanni Beccaro
相关产品推荐
相关产品推荐

