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
2 Answers
Reset to default 8It 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
版权声明:本文标题:javascript - How do I strip bad chars from a string in JS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741298134a2370936.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论