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?
You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.
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.
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With