Tricky Javascript regex replace
<p>I'm coding a custom markdown parser that should preprocess user input so that each line of the input that starts with three ticks should have the reference code trimmed and all it's spaces replaced with underscores. So in this fiddle</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var e = document.getElementById("thetext");
var feedback = document.getElementById("feedback");

var sorted = function(haystack) {
  var re = /$```\s*(\S+)(\s+)(\S+)\s*$/g;
  return haystack.replace(re, '```$1_$3');
};

e.addEventListener("blur", function(event) {
  feedback.innerHTML = sorted(e.value);
}, true);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { width: 400px; height: 400px;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;textarea id="thetext"&gt;
A custom block code marker with reference:

``` John 3:16
For God so loved the world 
``` 

another one with two spaces to be replaced:

```1 Cor 2:15-45 
Some other marked up text followed by white space 
```

&lt;/textarea&gt;
&lt;pre id="feedback"&gt;Tab out to see result&lt;/pre&gt;</code></pre>
</div>
</div>
</p>

<p>the output should be exactly like the input except for these two lines:</p>

<pre>
```John_3:16
</pre>

<p>and</p>

<pre>
```1_Cor_2:15-45
</pre>