Effect example
//First: screening discoloration (recommended)
KeyRegExp:function(val, keyword) { val = val + ''; if (val.indexOf(keyword) !== -1 && keyword !== '') { return val.replace(keyword, '<font color="#f00">' + keyword + '</font>') } else { return val } },
//Second: regular expressions
KeyRegExp:function(val, keyword) { var Reg = new RegExp(keyword, 'i'); if (val) { return val.replace(Reg, `<span style="color: #f00;">${keyword}</span>`); } },
//Third: regular expression (for the second optimization)
keyRegExp:function (str,key){ // Search key highlight // Regular matching Chinese and English keywords are highlighted, and the highlighted keywords are consistent with the previous case var key = key;//Key words defined here key = '('+key.replace(/([\+\.\*\|\?\-\(\[\^\$])/g,'\\$1' ).replace(/\s+/g,'|')+')';//Escape the regular characters in matching keywords var patt = new RegExp(key ,'igm'); //pass igm Avoid text mismatch caused by spaces after keywords var str2 = str.replace(patt,"<span style='color:#f00;'>$1</span>"); return str2; },
usage method
<p v-html="keyRegExp(String to filter,keyword)"></p>
/ / fourth: slice clipping of js (not recommended)
<p class="text" v-if="picked=='ap'" @click="listFn(item,'ap')"> <span>{{item.ap.slice(0,item.ap.toLowerCase().indexOf(apVal.toLowerCase()))}}</span> <span style="color:#f00">{{item.ap.slice(item.ap.toLowerCase().indexOf(apVal.toLowerCase()),item.ap.toLowerCase().indexOf(apVal.toLowerCase())+apVal.length)}}</span> <span>{{item.ap.substr(item.ap.toLowerCase().indexOf(apVal.toLowerCase())+apVal.length)}}</span> </p>
Advantages and disadvantages of four methods
The first kind of filtering: the keyword can be filtered normally, but the space cannot be filtered
The second type is regular: Keywords can be filtered out, but Chinese and English brackets and spaces are not supported, and English brackets will report errors
The third type of regularity: Keywords can be filtered out, and Chinese brackets are supported. Adding spaces after keywords does not affect filtering, but English brackets are also not supported, and errors will be reported by English brackets
Fourth: if it is normal input, it can be filtered out, but the second input or adding space will produce an unfriendly rendering (before the request does not come back), you can feel it if you are OK
Error reporting instance