How to create a string "replace all" function?
<p>Every article or question I've seen pretty much says, just use:</p>

<pre><code>str.replace(/yourstring/g, 'whatever');
</code></pre>

<p>But I want to use a variable in place of "yourstring". Then people say, just use <code>new RegExp(yourvar, 'g')</code>. The problem with that is that <code>yourvar</code> may contain special characters, and I don't want it to be treated like a regex. </p>

<p>So how do we do this properly?</p>

<hr>

<p>Example input:</p>

<pre><code>'a.b.'.replaceAll('.','x')
</code></pre>

<p>Desired output:</p>

<pre><code>'axbx'
</code></pre>

<hr>

<h1>Solution 1</h1>

<pre><code>RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&amp;");
}

String.prototype.replaceAll = function(search, replace) {
    return this.replace(new RegExp(RegExp.escape(search),'g'), replace);
};
</code></pre>

<h1>Solution 2</h1>

<pre><code>'a.b.c.'.split('.').join('x');
</code></pre>

<hr>

<p><a href="http://jsperf.com/string-replaceall2" rel="nofollow">jsPerf Test</a></p>
