title: Is there a better way to sanitize input with javascript?
body: <p>I wanted to write a javascript function to sanitize user input and remove any unwanted and dangerous characters.</p>
  
  <p>It must allow only the following characters:</p>
  
  <ul>
  <li>Alfanumeric characters (case insentitive): [a-z][0-9].</li>
  <li>Inner whitespace, like "word1 word2".</li>
  <li>Spanish characters (case insentitive): [áéíóúñü].</li>
  <li>Underscore and hyphen [_-].</li>
  <li>Dot and comma [.,].</li>
  <li>Finally, the string must be trimmed with trim().</li>
  </ul>
  
  <p>My first attempt was:</p>
  
  <pre><code>function sanitizeString(str){
  str = str.replace(/[^a-z0-9áéíóúñü_-\s\.,]/gim,"");
  return str.trim();
  }
  </code></pre>
  
  <p>But if I did:</p>
  
  <pre><code>sanitizeString("word1\nword2")
  </code></pre>
  
  <p>it returns:</p>
  
  <pre><code>"word1
  word2"
  </code></pre>
  
  <p>So I had to rewrite the function to remove explícitly \t\n\f\r\v\0:</p>
  
  <pre><code>function sanitizeString(str){
  str = str.replace(/([^a-z0-9áéíóúñü_-\s\.,]|[\t\n\f\r\v\0])/gim,"");
  return str.trim();
  }
  </code></pre>
  
  <p>I'd like to know:</p>
  
  <ol>
  <li>Is there a better way to sanitize input with javascript?</li>
  <li>Why \n and \t doesn't matches in the first version RegExp?</li>
  </ol>