JS and regular expression for replacing everthing inside double = mark

Viewed 62

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!

5 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)

Here you go! This is a solution using super secret regex replace function techniques.

var testString = "Edit the ==Expression=\n== & T==sa==ext to see matches.";
console.log(testString);
console.log(testString.replace(/={2}([^=]=?)*={2}/g, function(match){
    return match.replace("==","<span class=\"highlight\">").replace("==","</span>");
}));

You can also use the following regex:

={2}(.*?)(?<!==)={2}

use a back reference to \1 and surround it with <span class="highlight"> and </span>. (however Mark Meyer solution is more direct and better as Lookbehinds are only available in browsers supporting ECMA2018 standard)

Demo: https://regex101.com/r/UaFVeh/1/

Here is the entire solution to my question: replace == surounded text with <span class="highlight"> </span>.

<!DOCTYPE html>
<html lang="en">
<style>
  .highlight {
    background-color: yellow
  }
</style>

<body>
  <p>
    == asddac == awdawd = awda ==wad == ==d==
  </p>
</body>
<script>
  document.body.innerHTML = document.body.innerHTML.replace(/==([\s\S]*?)==/g, "<span class=\"highlight\">$1</span>");
</script>

</html>

This uses lazy quantifiers and backreferences.

==(.*?)== Regex101 demo

Related