Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect non-printable characters in JavaScript

Is it possible to detect binary data in JavaScript?

I'd like to be able to detect binary data and convert it to hex for easier readability/debugging.


After more investigation I've realized that detecting binary data is not the right question, because binary data can contain regular characters, and non-printable characters.

Outis's question and answer (/[\x00-\x1F]/) is really the best we can do in an attempt to detect binary characters.

Note: You must remove line feeds and possibly other characters from your ascii string sequence for the check to actually work.

like image 290
deepwell Avatar asked Nov 05 '09 00:11

deepwell


People also ask

How do I find non-printable characters in a text file?

You can download Notepad++ and open the file there. Then, go to the menu and select View->Show Symbol->Show All Characters . All characters will become visible, but you will have to scroll through the whole file to see which character needs to be removed.

How do you remove non-ascii characters?

Use . replace() method to replace the Non-ASCII characters with the empty string.


1 Answers

If by "binary", you mean "contains non-printable characters", try:

/[\x00-\x1F]/.test(data)

If whitespace is considered non-binary data, try:

/[\x00-\x08\x0E-\x1F]/.test(data)

If you know the string is either ASCII or binary, use:

/[\x00-\x1F\x80-\xFF]/.test(data)

or:

/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(data)
like image 186
outis Avatar answered Oct 12 '22 11:10

outis