Created
May 28, 2012 14:11
-
-
Save lsauer/2819387 to your computer and use it in GitHub Desktop.
Javascript - Replacing the escape character in a string literal
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
//www.lsauer.com 2012 | |
//Answer to: http://stackoverflow.com/questions/1376440/javascript-replacing-the-escape-character-in-a-string-literal/10785991#10785991 | |
//To better demonstrate and understand the string-escaping behavior of JS, take the following example: | |
//You can see what the string looks like in memory after being parsed by the JS-engine by splitting the string, | |
//thus also offering potential (ugly) solutions around this issue: | |
'file:///C:\funstuff\buildtools\viewer.html'.split('') | |
//> | |
["f", "i", "l", "e", ":", "/", "/", "/", "C", ":", "", "u", "n", "s", "t", "u", | |
"f", "f", "", "u", "i", "l", "d", "t", "o", "o", "l", "s", "", "i", "e", "w", | |
"e", "r", ".", "h", "t", "m", "l"] | |
'file:///C:\funstuff\buildtools\viewer.html'.split('').map( function(e){ | |
return e.charCodeAt() | |
}); | |
//> | |
[102, 105, 108, 101, 58, 47, 47, 47, 67, 58, 12, 117, 110, 115, 116, 117, 102, | |
102, 8, 117, 105, 108, 100, 116, 111, 111, 108, 115, 11, 105, 101, 119, 101, | |
114, 46, 104, 116, 109, 108] | |
//>in Hex values by applying .toString(16) | |
["66", "69", "6c", "65", "3a", "2f", "2f", "2f", "43", "3a", "c", "75", "6e", | |
"73", "74", "75", "66", "66", "8", "75", "69", "6c", "64", "74", "6f", "6f", | |
"6c", "73", "b", "69", "65", "77", "65", "72", "2e", "68", "74", "6d", "6c"] | |
//Basically the single backslash escapes the following character, | |
//thus giving rise to unexpected results, if the escaping-context is not heeded. | |
//#Solution: | |
//Through a look-up-table, you can restore many errantly escaped characters if they | |
//lie outside the printable ASCII character range of `\x20-\x7F`. | |
//For the example above for instance, 12 or \x0c [ 12..toString(16) ] would become '\\'+'v', and so on. | |
//PS: Be aware that a loss of information occured, and you are trying to restore information | |
//through contextual- or meta- information, meaning in your case that the string is in the printable ASCII range. | |
//Please share any implementations with the community. Cheers! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment