Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple ascii replacement - Javascript

I'm looking for a javascript function which takes a string parameter and checks for ascii characters lower than 32, replacing them with empty string -> "". I'm new to javascript so I was wondering whether anyone can point me towards the right direction ?

Thanks in advance for your time.

like image 336
Pumpkin Avatar asked Sep 01 '26 00:09

Pumpkin


2 Answers

Try this:

var replaced = string.replaceAll("[^ -~]", "");

Using ^ negates the characters class, and since space is character 32 in the ASCII table and ~ is the last printable character, you're basically saying "everything that isn't a printable character".

To simply remove all characters from 0-31 use:

var replace = string.replaceAll("\x00-\x1F", "");
like image 84
Sean Airey Avatar answered Sep 03 '26 13:09

Sean Airey


If I understand your question correctly you are looking for a regex to use with .replace...

For replacing any printable ascii chars you can use this regex:

/[ -~]/

You will probably have to adjust the range. I recommend changing the tilder since it is the last printable char.

Sorry, I see what you mean! I think you cannot match unprintable chars unless use use their special symbol: i.e. \b \s \n etc.

like image 27
Joseph Adams Avatar answered Sep 03 '26 14:09

Joseph Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!