gpt4 book ai didi

javascript - 用于替换 double = mark 中所有内容的 JS 和正则表达式

转载 作者:行者123 更新时间:2023-11-29 10:02:12 24 4
gpt4 key购买 nike

我正在尝试在 GitHub 页面上写博客。但是 GFM 不像 typora 那样支持高亮文本。我想做的是匹配一对“==”之间的所有内容(包括换行符)。所以应该选择下面的文字

Edit the ==Expression=
== & T==sa==ext to see matches.

并改为

Edit the <span class="highlight">Expression=
</span> & T<span class="highlight">sa</span>ext to see matches.

我想问的是

  1. 我应该使用什么正则表达式来匹配?我得到了 ={2}[^=]*={2} 但那是不对的。
  2. 是否有任何简单的 js 可以替换?我希望我的网站尽可能少地使用 JS。

非常感谢!

最佳答案

您可以使用反向引用和 s 标志非常干净地完成此操作:

let str = `Edit the ==Expression=
== & T==sa==ext to see matches.`

let tags = str.replace(/==(.*?)==/gs, '<span class="highlight">$1</span>')
console.log(tags)

如果您工作的环境中 s 标志尚不可用,您还可以使用 [\s\S] 来匹配文本,包括换行符:

let str = `Edit the ==Expression=
== & T==sa==ext to see matches.`

let tags = str.replace(/==([\s\S]*?)==/g, "<span>$1</span>")
console.log(tags)

关于javascript - 用于替换 double = mark 中所有内容的 JS 和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com