Example: Result Text contentText
: " Seismic Acquisition Test ", Keyword keyword
: " Acquisition "
1. Obtain the common value of the result text contentText
and the keyword keyword
, that is, find the same word and store it in an array wordsArray, as follows:
//获取需要标红的文字
getRedWords(contentText, keyword) {
let keywordArray = keyword.split('');
let wordsArray = [];
for(let key of keywordArray){
if(contentText.includes(key)){
wordsArray.push(key)
}
}
return wordsArray;
},
Get the result wordsArray:
2. Use regular expressions to replace the text in each wordsArray for contentText in turn (the default text is replaced with a red format), as follows: (At this time, case matching is ignored, and the actual
measurement RegExp(word, 'i')
is a match. If you want If you want to match multiple times, you can use RegExp(word, 'g')
global matching. For details, please go to: Regular Expression Matching Individuals can choose according to the actual situation)
//将文字标红
brightenKeyword(contentText, keyword) {
let wordsArray = this.getRedWords(contentText, keyword);
let res = contentText;//res的初始值是不带任何红色格式的
//遍历相同字数组,
for(let word of wordsArray){
const Reg = new RegExp(word, 'i');
//替换每一个相同字
res = res.replace(Reg, `<span style="color: red;">${
word}</span>`);
}
return res;//此时的res里已经将需要标红的字体带上了格式(<span style="color:red"></span>)
},
3. Call the brightenKeyword method, get the return value, and use the label to display the result, as follows:
<span v-html="brightenKeyword(record.productName,oldSearchText)"></span>
4. The final result: