> 技术文档 > 高亮标题里的某个关键字正则表达式

高亮标题里的某个关键字正则表达式

 

使用v-html渲染,写一个高亮方法

 这里传入的name带了文件拓展名,所以先把名称从文件名里提取出来

// 高亮标题颜色 highlightKeywords(name, keywords) { // 安全处理空值 if (!name || typeof name !== \'string\') return \'\'; // 正则解释: // .*? 非贪婪匹配任意字符(尽可能少匹配) // (?=\\.[^.]+$) 正向肯定预查:匹配后面紧跟着\"点+扩展名\"的位置 const match = name.match(/.*?(?=\\.[^.]+$)/); // 如果有匹配结果则返回,否则返回原名称(无扩展名的情况) const title = match ? match[0] : name; // console.log(title, \'--title--\') // console.log(match, \'--match--\') // 统一处理:将单个关键词转为数组,方便统一逻辑 const keywordList = Array.isArray(keywords) ? keywords : [keywords]; // 过滤空关键词 const validKeywords = keywordList.filter(k => k && k.trim() !== \'\'); if (validKeywords.length === 0) return title; // 构建正则表达式:匹配所有关键词(不区分大小写) // 转义特殊字符,避免正则语法错误 const escapedKeywords = validKeywords.map(k =>  k.replace(/[.*+?^${}()|[\\]\\\\]/g, \'\\\\$&\') // 转义正则特殊字符 ); const regex = new RegExp(`(${escapedKeywords.join(\'|\')})`, \'gi\'); // 替换匹配到的关键词,添加高亮样式 return title.replace(regex, (match) => { return `${match}`; }); },