Created
December 5, 2011 02:41
-
-
Save gerardpaapu/1432072 to your computer and use it in GitHub Desktop.
Remove non-ascii characters from javascript strings
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 toAscii(src) { | |
| var ch, str, i, result = ''; | |
| // `str` should now be 'double-escaped' e.g. a newline in the | |
| // original `src` should be represented by '\\n' in `str` | |
| str = JSON.stringify(str); | |
| // we start from str[1] and stop at str[-1] to | |
| // drop the opening and closing quote marks when | |
| // using JSON.stringify | |
| for (i = 1; i < str.length - 1; i++) { | |
| // May need to use a "fixed" version | |
| // of charCodeAt as discussed here | |
| // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt | |
| ch = str.charCodeAt(i); | |
| if (ch < 128) { | |
| result += str.charAt(i); | |
| } else { | |
| result += '\\u' + ch.toString(16); | |
| } | |
| } | |
| } | |
| function fromAscii(str) { | |
| return JSON.parse('"' + str + '"'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment