- 在不考慮關鍵字是特殊字符的情況下:
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('要檢索的內容','檢索的關鍵字','給內容中的關鍵字加上的有特殊標記的標籤名')
2.如果關鍵字允許是特殊字符的情況下,就要做區別處理,因爲有些特殊字符在正則中有特殊含義(例如:^\*+?等,具體可參考正則表達式手冊):
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('要檢索的內容','檢索的關鍵字','給內容中的關鍵字加上的有特殊標記的標籤名')。
本篇文章主要用來記載工作項目中遇到的,本人覺得有必要記下來的知識點,方便在以後遇到時可以直接使用,也給遇到同樣問題的其他人提供一個思路。