admin管理员组

文章数量:1287593

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?

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?

Share Improve this question edited Aug 25, 2018 at 9:31 yugr 22k4 gold badges59 silver badges104 bronze badges asked Aug 6, 2009 at 16:33 Robin RodricksRobin Rodricks 114k147 gold badges414 silver badges617 bronze badges 1
  • 1 What causes those strange characters? It would be better to investigate the root cause and fix it there. – Chetan S Commented Aug 6, 2009 at 16:49
Add a ment  | 

2 Answers 2

Reset to default 8

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

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

本文标签: javascriptHow do I strip bad chars from a string in JSStack Overflow