从字符串正则表达式操作中排除降价中的 URLs/Images

Excluding URLs/Images in markdown from string Regular Expression operation

我正在构建一个应用程序,用户可以在该应用程序中突出显示并滚动到他们在搜索栏中撰写的文章中的单词。文章采用 Markdown 格式,我使用 Markdown-it 呈现文章正文。

除非他们搜索的词是图像的一部分,否则效果很好 URL。它对其应用正则表达式并中断图像。

    applyHighlights() {
      let str = this.article.body
      let searchText = this.articleSearchAndLocate
      const regex = new RegExp(searchText, 'gi')
      let text = str
      if (this.articleSearchAndLocate == '') {
        return text
      } else {
        const newText = text.replace(
          regex,
          `<span id="searchResult" class="rounded-sm shadow-xl py-0.25 px-1 bg-accent font-semibold text-tint">$&</span>`
        )
        return newText
      }
    }

如果是图像 URL,有没有办法排除应用正则表达式?

您可以使用

applyHighlights() {
  let str = this.article.body
  let searchText = this.articleSearchAndLocate
  const regex = new RegExp('(!\[[^\][]*]\([^()]*\))|' + searchText.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&'), 'gi')
  let text = str
  if (this.articleSearchAndLocate == '') {
    return text
  } else {
    const newText = text.replace(
     regex, function(x, y) { return y ? y :
      '<span id="searchResult" class="rounded-sm shadow-xl py-0.25 px-1 bg-accent font-semibold text-tint">' + x + '</span>'; })
    return newText
  }
}

这里,

  • new RegExp('(!\[[^\][]*]\([^()]*\))|' + searchText.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&'), 'gi') - 创建一个像 (!\[[^\][]*]\([^()]*\))|hello 这样的正则表达式,它匹配并捕获到组 1 中的字符串,如 ![desc](value),或者它匹配 hellow(如果 searchTexthello).
  • .replace(regex, function(x, y) { return y ? y : '<span id="searchResult" class="rounded-sm shadow-xl py-0.25 px-1 bg-accent font-semibold text-tint">' + x + '</span>'; }) 表示如果第 1 组 (y) 匹配,则 return 值是 y 本身(不进行替换),否则, x(整场比赛,searchText)用 span 标签包裹
  • .replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&') 是支持可以包含特殊正则表达式元字符的 searchText 所必需的,请参阅 Is there a RegExp.escape function in JavaScript?