搜索高亮

1、使用replace方法(推薦)spa

function getHighlightText({keyWord, text} = {}) {get

  if (!keyWord || !text) { string

    return text it

  } io

  const condition = '(' + keyWord + ')'ast

  const reg = new RegExp(condition, 'ig')function

  return text.replace(reg, '<span class="high-light">$1</span>')class

}方法

2、使用RegExp的exec方法di

function getHighlightText({keyWord, text} = {}) {

  if (!keyWord || !text) {

    return text

  }

  const reg = new RegExp(keyWord, 'ig')

  let result

  let highlightText = ''

  let nexIndex = 0

   while ((result = reg.exec(text)) !== null) {

    highlightText +=  text.substring(nexIndex, result.index) + `<span class="high-light">${result[0]}</span>`

    nexIndex = reg.lastIndex

  }

  if (nexIndex !== text.length - 1) {

    highlightText += text.substring(nexIndex)

   }

  return highlightText

}

相關文章
相關標籤/搜索