Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS and regular expression for replacing everthing inside double = mark

I am trying to write a blog on GitHub pages. But the GFM does not support highlight text like typora does. What I want to do is to match everything (including line breaks) in between a pair of "==". So the following text should be selected

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

and changed to

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

What I am asking is that

  1. What regular expression should I use to match? I got ={2}[^=]*={2} but that's not right.
  2. Is there any simple js I can do the replacement? I want my website to use as little JS as possible.

Thanks a lot!

like image 356
wooohooo Avatar asked Feb 02 '26 10:02

wooohooo


1 Answers

You can do this pretty cleanly with back references and the s flag:

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

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

On the chance you are working in an environment where the s flag doesn't yet work you can also use [\s\S] to match the text including line breaks:

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

let tags = str.replace(/==([\s\S]*?)==/g, "<span>$1</span>")
console.log(tags)
like image 104
Mark Avatar answered Feb 04 '26 22:02

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!