Core JavaScript

Remove Non-Printable ASCII Characters

This JavaScript example uses the paste event in a textarea element to remove the non-printable characters from a string. To remove non-printable characters, copy a text select from some source, using control-c. Then select the textarea below and press control-v to paste it into the textarea. The program automatically removes any non-printable characters from the string. That is, all standard keyboard characters remain, including tabs, carriage returns and line feed characters.

Once the text is pasted into the textarea, you can press control-a to select it all from the textarea and control-c to copy the clean text. A sample text string is provided for testing.

RemoveNonPrintableChars.html

<!DOCTYPE html>
<html>
	<head>
  	<title>XoaX.net's Javascript</title>
  	<script type="text/javascript" src="RemoveNonPrintableChars.js"></script>
	</head>
	<body>
		<p>Copy this test text and paste it below to verify that it works: &#xCB;I&frac12;t &auml;W&#222;o&Ocirc;r&eth;k&#xF5;s&ugrave;!&para;</p>
		<textarea id="idText" onpaste="OnPaste()" rows="50" cols="100" style="width:100%;border:1px black solid;background-color:lightgray;"></textarea>
	</body>
</html>

RemoveNonPrintableChars.js

function OnPaste() {
  event.preventDefault();
  let sPaste = (event.clipboardData || window.clipboardData).getData("text");
  const selection = window.getSelection();
  if (!selection.rangeCount) return;
  var sCleanText = RemoveNonPrintableAsciiChars(sPaste);
  document.getElementById("idText").innerHTML = sCleanText;
}

function RemoveNonPrintableAsciiChars(sDirty) {
  // Check if the input string is null or empty.
  if ((sDirty===null) || (sDirty===''))
    return '';
  else
    sDirty = sDirty.toString();
  // The range for 32 = space to 126 = tilde with tab, linefeed, and carriage return
  return sDirty.replace(/[^\x20-\x7E|^\x09-\x0A|\x0D]/g, '');
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.