Created
September 22, 2016 15:02
-
-
Save subzey/21483cb89f4027898cdf2bdf625f94a2 to your computer and use it in GitHub Desktop.
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
| // Create regexp once | |
| var reUnicode = /[\u0080-\uFFFF]/g; | |
| // Create functor once | |
| function _unicodeEscape(character) { | |
| return '\\u' + ('000' + character.charCodeAt(0).toString(16)).slice(-4); | |
| } | |
| function escapeJSON(jsonStr) { | |
| // This function only accepts valid JSON strings | |
| return jsonStr.replace(reUnicode, _unicodeEscape); | |
| } | |
| // Usage: | |
| var str = escapeJSON(JSON.stringify( | |
| { | |
| "проверка": "проверка", | |
| "\r\n\t": true | |
| } | |
| )); | |
| console.assert(JSON.parse(str)['проверка'] === 'проверка'); // Should work | |
| console.assert(JSON.parse( | |
| escapeJSON('"\\u0442ест"') | |
| ) === 'тест'); // Should not escape already escaped chars |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment