warpTag (content, keyword, tagName) { if (content === 'No results') { return content } const a = content.toLowerCase() const b = keyword.toLowerCase() const indexof = a.indexOf(b) const c = indexof > -1 ? content.substr(a.indexOf(b), keyword.length) : '' const val = `<${tagName}>${c}</${tagName}>` const regS = new RegExp(keyword, 'gi') return content.replace(regS, val) }
调用的时候warpTag('要检索的内容','检索的关键字','给内容中的关键字加上的有特殊标记的标签名')html
2.若是关键字容许是特殊字符的状况下,就要作区别处理,由于有些特殊字符在正则中有特殊含义(例如:^\*+?等,具体可参考正则表达式手册):jquery
warpTag (content, keyword, tagName) { if (content === '') { return content } const a = content.toLowerCase() const b = keyword.toLowerCase() const indexof = a.indexOf(b) const c = indexof > -1 ? content.substr(a.indexOf(b), keyword.length) : '' const val = `<${tagName} class='keywords'>${c}</${tagName}>` let characterReg = /^.*[\\!~@#$%^&*(_)+\-=`,./<>?;':"|[\]{}].*$/ let regS if (characterReg.test(keyword)) { if (keyword.length === 1) { regS = new RegExp('\\' + keyword, 'gi') } else { let keywordNew = '' for (let i = 0; i < keyword.length; i++) { keywordNew += i < keyword.length - 1 ? keyword.substr(i, 1) + '\\' : keyword.substr(i, 1) } keyword = keywordNew } regS = new RegExp('\\' + keyword, 'gi') } else { regS = new RegExp(keyword, 'gi') } return content.replace(regS, val) }
使用方法同上:warpTag('要检索的内容','检索的关键字','给内容中的关键字加上的有特殊标记的标签名')。
本篇文章主要用来记载工做项目中遇到的,本人以为有必要记下来的知识点,方便在之后遇到时能够直接使用,也给遇到一样问题的其余人提供一个思路。正则表达式