views:

278

answers:

2

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?

+1  A: 

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
Amber
+3  A: 

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,'');
Josh Stodola