Skip to content

Instantly share code, notes, and snippets.

@kerspoon
Created August 16, 2011 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerspoon/1150355 to your computer and use it in GitHub Desktop.
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.
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