Consecutive duplicate words to change with regex
<pre><code>var str="Foo bar bar end."
var word="bar"
var regex = new RegExp("([\\s]|^|&gt;)("+word+")(&lt;|[\\s]|$)", "gi");
str=str.replace(regex,' &lt;span class="selected"&gt;$2&lt;/span&gt; ');
</code></pre>

<p>result: </p>

<pre><code>Foo &lt;span class="selected"&gt;bar&lt;/span&gt; bar end.
</code></pre>

<p>Why only first <code>bar</code> changed?</p>