Created
August 16, 2011 22:31
-
-
Save kerspoon/1150355 to your computer and use it in GitHub Desktop.
Escape the required characters and surround with double quotes to produce a valid ECMAScript string literal from any normal string.
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
def escape_as_javascript_string_literal(text): | |
""" | |
Escape the required characters and surround with double quotes to produce a | |
valid ECMAScript string literal from any normal string. | |
---- | |
ECMA-262 -> 7.8.4 String Literals | |
A string literal is zero or more characters enclosed in single or | |
double quotes. Each character may be represented by an escape | |
sequence. All characters may appear literally in a string literal | |
except for the closing quote character, backslash, carriage return, | |
line separator, paragraph separator, and line feed. Any character may | |
appear in the form of an escape sequence. | |
ECMA-262 -> 7.3 Line Terminators | |
\u000A Line Feed <LF> \n | |
\u000D Carriage Return <CR> \r | |
\u2028 Line separator <LS> | |
\u2029 Paragraph separator <PS> | |
Note: esacping the single quote is not required as we use double quotes. | |
""" | |
new_text = ""; | |
for char in text: | |
# closing quote character | |
if char is '"': | |
new_text += "\\" + "\"" | |
# backslash | |
if char is '\\': | |
new_text += "\\" + "\\" | |
# carriage return, | |
if char is '\r': | |
new_text += "\\" + "r" | |
# line separator, | |
if char is '\u2028': | |
new_text += "\\" + "u2028" | |
# paragraph separator, | |
if char is '\u2029': | |
new_text += "\\" + "u2029" | |
# line feed | |
if char is '\n': | |
new_text += "\\" + "n" | |
# otherwise normal | |
else: | |
new_text += char | |
return "\"" + new_text + "\"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment