Filter the search keywords of the article and show one of the highlighted javascript implementation methods

  1. Regardless of whether the keyword is a special character:
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)
    }

When calling, warpTag('content to be retrieved ',' keyword to be retrieved ',' tag name with special tag added to keyword in content ')

2. If the keyword is allowed to be a special character, differential processing should be done, because some special characters have special meanings in the regular (for example: ^ \ * +? Etc., for details, please refer to Regular expression manual):

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)
  }

The usage method is the same as above: warpTag('content to be retrieved ',' keyword to be retrieved ',' tag name with special tag added to keyword in content ').
This article is mainly used to record the knowledge points encountered in the work project that I think it is necessary to write down, which can be used directly in the future, and also provide a way for other people who encounter the same problem.

Tags: Javascript

Posted on Mon, 02 Dec 2019 17:34:08 -0800 by Anyaer