If you are working with a JSON string, you have the option to utilize the reviver parameter in the JSON.parse(string, [reviver])
method:
var jsonStr = '{"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"}';
var result = JSON.parse(jsonStr, function (key, value) {
return value.replace(/ /g, " ");
});
Similarly, the stringify
method provides a replacer function that can replace specific values when converting to a JSON string:
var obj = {"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"};
var result = JSON.stringify(obj, function (key, value) {
return value.replace(/ /g, " ");
});
It is important to note that these features are available when using a library like json2.js or a browser that supports ECMAScript 5th Edition specifications for the JSON object.