How do you trim white spaces in both the keys and values in a JavaScript Object recursively?
I came across one issue in which I was trying to \"clean\" a user suppli
Similar to epascarello's answer. This is what I did :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
........
public String trimWhiteSpaceAroundBoundary(String inputJson) {
String result;
final String regex = "\"\\s+|\\s+\"";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(inputJson.trim());
// replacing the pattern twice to cover the edge case of extra white space around ','
result = pattern.matcher(matcher.replaceAll("\"")).replaceAll("\"");
return result;
}
Test cases
assertEquals("\"2\"", trimWhiteSpace("\" 2 \""));
assertEquals("2", trimWhiteSpace(" 2 "));
assertEquals("{ }", trimWhiteSpace(" { } "));
assertEquals("\"bob\"", trimWhiteSpace("\" bob \""));
assertEquals("[\"2\",\"bob\"]", trimWhiteSpace("[\" 2 \", \" bob \"]"));
assertEquals("{\"b\":\"bob\",\"c c\": 5,\"d\": true }",
trimWhiteSpace("{\"b \": \" bob \", \"c c\": 5, \"d\": true }"));