title: Javascript - Regex - how to filter characters that are not part of regex
body: <p>I want to accept words and some special characters, so if my regex
  does not fully match, let's say I display an error,</p>
  
  <pre><code>var re = /^[[:alnum:]\-_.&amp;\s]+$/;
  var string = 'this contains invalid chars like #@';
  var valid = string.test(re);
  </code></pre>
  
  <p>but now I want to "filter" a phrase removing all characters not matching the regex ?</p>
  
  <p>usualy one use replace, but how to list all characters not matching the regex ?</p>
  
  <pre><code>var validString = string.filter(re); // something similar to this
  </code></pre>
  
  <p>how do I do this ?</p>
  
  <p>regards</p>
  
  <hr>
  
  <p>Wiktor Stribiżew solution works fine :</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>regex=/[^a-zA-Z\-_.&amp;\s]+/g;
  let s='some bloody-test @rfdsfds';
  s = s.replace(/[^\w\s.&amp;-]+/g, '');
  console.log(s);</code></pre>
  </div>
  </div>
  </p>
  
  <p>Rajesh solution :</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>regex=/^[a-zA-Z\-_.&amp;\s]+$/;
  let s='some -test @rfdsfds';
  s=s.split(' ').filter(x=&gt; regex.test(x));
  console.log(s);</code></pre>
  </div>
  </div>
  </p>