Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created December 5, 2011 02:41
Show Gist options
  • Select an option

  • Save gerardpaapu/1432072 to your computer and use it in GitHub Desktop.

Select an option

Save gerardpaapu/1432072 to your computer and use it in GitHub Desktop.
Remove non-ascii characters from javascript strings
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