Skip to content

Instantly share code, notes, and snippets.

@uupaa
Created May 12, 2013 03:22
Show Gist options
  • Select an option

  • Save uupaa/5562297 to your computer and use it in GitHub Desktop.

Select an option

Save uupaa/5562297 to your computer and use it in GitHub Desktop.
JSON.stringify(string) polyfill
function _toJSONEscapedString(str) { // @arg String:
// @ret String:
// @inner: to JSON escaped string
var JSON_ESCAPE = {
'\b': '\\b', // backspace U+0008
'\t': '\\t', // tab U+0009
'\n': '\\n', // line feed U+000A
'\f': '\\f', // form feed U+000C
'\r': '\\r', // carriage return U+000D
'"': '\\"', // quotation mark U+0022
'\\': '\\\\' // reverse solidus U+005C
};
return str.replace(/(?:[\b\t\n\f\r\"]|\\)/g, function(_) {
return JSON_ESCAPE[_];
}).replace(/(?:[\x00-\x1f])/g, function(_) {
return "\\u00" +
("0" + _.charCodeAt(0).toString(16)).slice(-2);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment