Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre class="lang-js prettyprint-override"><code>str = str.replace(/abc/g, ''); </code></pre> <p>In response to comment:</p> <pre class="lang-js prettyprint-override"><code>var find = 'abc'; var re = new RegExp(find, 'g'); str = str.replace(re, ''); </code></pre> <p>In response to <a href="https://stackoverflow.com/users/49153/click-upvote">Click Upvote</a>'s comment, you could simplify it even more:</p> <pre class="lang-js prettyprint-override"><code>function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); } </code></pre> <p><strong>Note:</strong> Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the <code>find</code> function above without pre-processing it to escape those characters. This is covered in the <a href="https://developer.mozilla.org/en-US/" rel="noreferrer">Mozilla Developer Network</a>'s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters" rel="noreferrer">JavaScript Guide on Regular Expressions</a>, where they present the following utility function:</p> <pre class="lang-js prettyprint-override"><code>function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } </code></pre> <p>So in order to make the <code>replaceAll()</code> function above safer, it could be modified to the following if you also include <code>escapeRegExp</code>:</p> <pre class="lang-js prettyprint-override"><code>function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload