I have a text field, which will accept only the following characters:
Allowed characters: [a-z 0-9 + # - .]
This is the same filter SO>
You don't need to replace the char, only prevent it.
var char = String.fromCharCode(event.which) if (!char.match(/^[^A-Za-z0-9+#\.\-]+$/)) event.preventDefault();