Skip to content

Instantly share code, notes, and snippets.

@very
Created October 24, 2012 09:43
Show Gist options
  • Save very/3945168 to your computer and use it in GitHub Desktop.
Save very/3945168 to your computer and use it in GitHub Desktop.
function unescapeJSString(string) {
var named = {b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v"};
return string.replace(/\\(?:([bfnrtv])|u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2})|([0-3][0-7]{0,2}|[0-7]{1,2})|([^]))/g, function(seq, name, hex4, hex2, oct, char) {
var hex;
if (name) { // e.g. \n
return named[name];
} else if (char) { // e.g. \"
return char;
} else if (hex = hex4 || hex2) { // e.g. \u0022 or \x22
return String.fromCharCode(parseInt(hex, 16));
} else if (oct) { // e.g. \42
return String.fromCharCode(parseInt(oct, 8));
} else {
// this case doesn't happen actually
return seq;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment