Clean TextArea of Non-ASCII Characters with a regular expression.

April 20th, 2010

 

This TextArea below is an example, you have to move your pointer into and then out of the text box to execute the onBlur event that cleans the textarea.

This is my source:

<textarea rows=20 cols=50 onBlur='CleanUp(this);' >
Just try and type non ASCII text into this area!
</textarea>

<script language="JavaScript">
function CleanUp(ObjThis) {
    //Do not allow non-ASCII text!
    var str = ObjThis.innerText
    str = str.replace(/[^\x21-\x7E\s\t\n\r]+/g, '');
    ObjThis.innerText = str
}
</script>

The above script will replace anything outside of hex 21-7E with blanks .  The exception in (spaces, tabs, newline, return) 21-7E are ascii chars everything else is blanked out.