Live regular expression highlighting : <p>I am attempting to use JavaScript to highlight regular expression matches in real time. Similar to sites such as <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a></p>

<pre><code>&lt;p id="haystack"&gt; Sample text Sample Text Sample Text Sample Text &lt;/p&gt;

    &lt;form&gt;
      &lt;input id="needle" onkeyup="highlight('haystack')" onkeydown="highlight('haystack')" type="text" placeholder="Enter Pattern" autofocus&gt;
    &lt;/form&gt;


function highlight(e){

    var pattern = document.getElementById('needle');

    var consoleText = document.getElementById('haystack').innerHTML;

    consoleText = consoleText.replace(pattern.value,"replaced");

    document.getElementById('haystack').innerHTML = consoleText;
</code></pre>

<p>I'm very new to JavaScript. How can I achieve the desired effect?</p>
