目录
1、convertEnglishSymbolsToChinese方法
实现逻辑
- 利用正则表达式,将目标文案以及关键字中的符号,统一更改为中文符号;
- 将关键字更改为正则表达式格式,用于匹配目标文案;
- 使用正则表达式的exec方法,获取到匹配到的index;
- 利用index,将文案拼接得到想要的结果;如果不做这一步的话,最终结果会与原文案有差异,因为咱们的targetText是中英文符号转化后的;
- 利用index获取匹配到的内容时,可以使用span标签嵌套,并添加对应类名,用于高亮渲染;
- 使用:
- 在使用的地方使用import导入该方法,将目标文案以及匹配的文案传给方法,直接return就好;
- 在template中,使用v-html渲染结果;
- 在css文件中添加你想实现的高亮效果;
代码截图
实现代码
1、convertEnglishSymbolsToChinese方法
export default (targetText, keyWord="") => {
const symbolMap = {
'!': '!',
'?': '?',
',': ',',
'.': '。',
';': ';',
':': ':',
'(': '(',
')': ')',
'[': '【',
']': '】',
'{': '{',
'}': '}',
'<': '《',
'>': '》',
'&': '&',
'*': '*',
'+': '+',
'-': '-',
'/': '/',
'=': '=',
'%': '%',
'$': '¥',
'@': '@',
'#': '#',
'^': '^',
'|': '|',
'~': '~',
'`': '`',
'\\': '\',
'\"': '"',
'\'': ''',
};
const tempTargetText = targetText.replace(/[!?,.;:()\[\]{}<>&*+-/=%$@#^|\\~`'"]/g, (match) => symbolMap[match]);
if(!keyWord) {
return tempTargetText;
}
const tempKeyWord = keyWord.replace(/[!?,.;:()\[\]{}<>&*+-/=%$@#^|\\~`'"]/g, (match) => symbolMap[match]);
const escapedKeyword = tempKeyWord.replace(/[!?,.;::()\[\]{}<>&*+-/=%$@#^|\\~`'"]/g, '\\$&');
const regex = new RegExp(`(${escapedKeyword})`, "gi");
const regMatch = regex.exec(tempTargetText);
if(regMatch) {
const startIndex = regMatch.index;
const endIndex = startIndex + tempKeyWord.length;
const beforeText = targetText.substring(0, startIndex);
const activeText = targetText.substring(startIndex, endIndex);
const afterText = targetText.substring(endIndex);
const highlightedText = `<span class="highlight">${activeText}</span>`;
return beforeText + highlightedText + afterText;
}
return targetText;
}
2、页面使用
<template>
<div v-html="highlightTaskText(text)"></div>
</template>
<script>
import convertEnglishSymbolsToChinese from "../../config/convertEnglishSymbolsToChinese";
export default {
methods: {
// 内容根据搜索项高亮显示
highlightTaskText(text) {
if (!this.taskNameKeyWord) {
return text;
}
return convertEnglishSymbolsToChinese(text, this.taskNameKeyWord);
},
}
}
</script>
<style lang="scss" scoped>
.highlight {
color: #de3326;
}
</style>