一、使用replace方法(推荐)

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

  if (!keyWord || !text) {

    return text

  }

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

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

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

}

二、使用RegExp的exec方法

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

}