Guest User

Untitled

a guest
Jan 24th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. def escape_as_javascript_string_literal(text):
  2. """
  3. Escape the required characters and surround with double quotes to produce a
  4. valid ECMAScript string literal from any normal string.
  5.  
  6. ----
  7.  
  8. ECMA-262 -> 7.8.4 String Literals
  9.  
  10. A string literal is zero or more characters enclosed in single or
  11. double quotes. Each character may be represented by an escape
  12. sequence. All characters may appear literally in a string literal
  13. except for the closing quote character, backslash, carriage return,
  14. line separator, paragraph separator, and line feed. Any character may
  15. appear in the form of an escape sequence.
  16.  
  17. ECMA-262 -> 7.3 Line Terminators
  18.  
  19. \u000A Line Feed <LF> \n
  20. \u000D Carriage Return <CR> \r
  21. \u2028 Line separator <LS>
  22. \u2029 Paragraph separator <PS>
  23.  
  24. Note: esacping the single quote is not required as we use double quotes.
  25. """
  26.  
  27. new_text = "";
  28. for char in text:
  29. # closing quote character
  30. if char is '"':
  31. new_text += "\\" + "\""
  32. # backslash
  33. if char is '\\':
  34. new_text += "\\" + "\\"
  35. # carriage return,
  36. if char is '\r':
  37. new_text += "\\" + "r"
  38. # line separator,
  39. if char is '\u2028':
  40. new_text += "\\" + "u2028"
  41. # paragraph separator,
  42. if char is '\u2029':
  43. new_text += "\\" + "u2029"
  44. # line feed
  45. if char is '\n':
  46. new_text += "\\" + "n"
  47. # otherwise normal
  48. else:
  49. new_text += char
  50. return "\"" + new_text + "\""
Add Comment
Please, Sign In to add comment