// 高亮匹配关键词样式----------------------------------------
replaceHTMLChar: s => s.toString().replace(/</g, `<`).replace(/>/g, `>`),
highLightMatchString(originStr, matchStr, customClass = ``) {
matchStr && (matchStr = matchStr.replace(/[.*+?^${}()|[\]\\]/g, ``));//过滤掉字符串里面的出现的正则表达式字符
if (matchStr === ``) return originStr;
customClass === true && (customClass = `sg-search-word-highlight`);
let newRepStr = (match = matchStr) => customClass ? `<span class=${customClass}>${this.replaceHTMLChar(match)}</span>` : `<b style='color:red;font-weight:bold;'>${this.replaceHTMLChar(match)}</b>`;
// return this.replaceHTMLChar(originStr).replace(new RegExp(this.replaceHTMLChar(matchStr), `gi`), newRepStr(matchStr));
return this.replaceHTMLChar(originStr).replace(new RegExp(this.replaceHTMLChar(matchStr), `gi`), (match, index) => newRepStr(match));// 返回原始匹配项,如果不希望替换,可以返回match
},
// 不对空格 < > 进行转义
highLightMatchStringIgnoreHTML(originStr, matchStr, customClass = ``) {
customClass === true && (customClass = `sg-search-word-highlight`);
matchStr && (matchStr = matchStr.replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\[/g, "\\[").replace(/\]/g, "\\]"));//避免括号被误认为是正则表达式的一部分
let newRepStr = customClass ? `<span class=${customClass}>${matchStr}</span>` : `<b style='color:red;font-weight:bold;'>${matchStr}</b>`;
return originStr.replace(new RegExp(matchStr, `gi`), newRepStr);
},
// 高亮关键词
highlightKeyword({ label, keyword, className = `highlight-keyword` }) {
return this.highLightMatchString(label, (keyword || ``).trim(), className);
},
// ----------------------------------------
高亮匹配关键词样式highLightMatchString、replaceHTMLChar
于 2025-07-23 13:16:02 首次发布