Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip bad chars from a string in JS?

My JS saves some string data to JSON using "stringify()", but observing the outputted JSON string I see a lot of strange chars (out of keyspace), such as NULLs and other bad chars. Now I don't have a list of these "bad" chars so how can I strip them out of my string data?

like image 272
Robin Rodricks Avatar asked Aug 06 '09 16:08

Robin Rodricks


People also ask

How do I remove unnecessary characters from a string?

You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.

How do I remove a character from a string in JavaScript?

JavaScript String replace() The replace() method is one of the most commonly used techniques to remove the character from a string in javascript. The replace() method takes two parameters, the first of which is the character to be replaced and the second of which is the character to replace it with.

How do you remove all characters from a string after a specific character in JavaScript?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str.


2 Answers

It would be nice if there was a simple RegEx for that, but I don't think there is. From what I understand, you still want to allow characters like %$#@, etc, but want to disallow other oddball chars like tabs and nulls. If this is correct, I believe the easiest way would be to loop each character and evaluate the char code...

function stripCrap(val) {
  var result = '';

  for(var i = 0, l = val.length; i < l; i++) {
    var s = val[i];
    if(String.toCharCode(s) > 31)
      result += s;
  }

  return result;
}

If you really want to use RegEx, a whitelist approach seems necessary. This will allow all numbers, letters, and a space...

val = val.replace(/[^a-z 0-9]+/gi,'');
like image 100
Josh Stodola Avatar answered Oct 26 '22 22:10

Josh Stodola


If you have a list of the "good" chars you could create a regex which matches any character not in your list, and strip anything it matches - for instance, the following regex matches anything not the letters "a", "q", or "z":

/[^aqz]+/ig
like image 25
Amber Avatar answered Oct 26 '22 23:10

Amber