3

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.

3
  • Also, why? Might be a better way. Commented Nov 15, 2012 at 13:26
  • stackoverflow.com/questions/94037/… this may help Commented Nov 15, 2012 at 13:27
  • What I meant was, I want to find and remove any characters within the string that has a lower ascii value than 32 Commented Nov 15, 2012 at 13:28

3 Answers 3

7

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", "");
Sign up to request clarification or add additional context in comments.

3 Comments

See my edit, I've included how to match specific character codes, with 1F being 31.
This will remove french letter à.
@Vitaly Not at desk ATM, which code is à? You could just add "^à" or "^{insert character code here}" to the regular expression to get it to exclude those from the replacement :)
1

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.

Comments

1
function keepCharsAbove(inStr, charCode) {
  var goodChars = [];
  for(var x = 0; x < inStr.length; x++) {
      if(inStr.charCodeAt(x) > charCode) {
          goodChars.push(inStr.charAt(x));
      }
  }

  return goodChars.join("");
}

​ Usage:

keepCharsAbove("foo \t bar",32); // returns 'foobar'

1 Comment

This would probably be better by converting the input to an array of single character strings, filtering the array (Array.filter) and then joining back into a string. (A more functional approach.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.