Created
May 12, 2013 03:22
-
-
Save uupaa/5562297 to your computer and use it in GitHub Desktop.
JSON.stringify(string) polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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