Javascript – Use Regex to INSERT text before and after a string pattern occurance

csshtmljavascriptregex

I am trying to replace all series of " " chars with "< pre> < /pre>" using a regular expression in Javascript.

So I want to change the 1st line below to the second:

<p>There   should    be    gaps    of    4    chars    tween    each    word</p>
<p>There<pre>   </pre>should<pre>    </pre>be<pre>    </pre>gaps<pre>    </pre>of<pre>    </pre>4<pre>    </pre>chars<pre>    </pre>tween<pre>    </pre>each<pre>    </pre>word</p>

// Or if I cannot place <pre>'s inside a <p> element then replace them with 
// transparent "_" chars
<p>There<font style="color: transparent">____</font>should...</p>

The reason I am doing this is because I am trying to preserve/display space chars and if I place the whole paragraph inside a pre element then word wrapping gets disabled.

Can you help me get my regular expression to place a pre start and end tag at the ends of each group of " " chars?

var p = document.getElementById("myP");
var con = p.innerHTML;
con = con.replace(new RegExp("[ ]{2,}"), "<pre> ");
con = con.replace(new RegExp("[ ]{2,}"), " </pre>");
p.innerHTML = con;

// This is incorrect because it removes all the space chars and only leaves one there
// Test    string
// Test<pre> </pre>string // there should be 4 space chars here

Best Answer

Capture the match with ( and ) then reference it with $1

var p = document.getElementById("myP");
var con = p.innerHTML;
con = con.replace(/(\s{2,})/g, "<pre>$1</pre>");