Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping JavaScript Strings in Python

I have a Python script that builds some JavaScript to send down to the browser in a JSON envelope. I'd like to escape the JavaScript strings and delimit them with single quotes. I can't use json.dumps because it uses double quotes as delimiters like the JSON spec requires.

Is there a JavaScript String escape method in Python?

Example

def logIt(self, str):
    #todo: need to escape str here
    cmd = "console.log('%(text)s');" % { 'text': str}
    json.dumps({ "script": cmd })

So logIt('example text') should return something like this:

{
  "script": "console.log('example text');"
}
like image 289
Lance Fisher Avatar asked Jun 14 '13 23:06

Lance Fisher


People also ask

How do you escape a string in Python?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do I escape a string in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

Do I need to escape in JavaScript string?

The only characters you normally need to worry about in a javascript string are double-quote (if you're quoting the string with a double-quote), single-quote (if you're quoting the string with a single-quote), backslash, carriage-return (\r), or linefeed (\n).

What does \r do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.


1 Answers

json.dumps is that escaping function - it takes any value, and makes it a valid javascript literal.

def logIt(self, str):
    cmd = "console.log({0});".format(json.dumps(str))
    json.dumps({ "script": cmd })

Producing:

>>> print logIt('example text')
{ "script": "console.log(\"example text\");" }
>>> print logIt('example "quoted" text')
{ "script": "console.log(\"example \\\"quoted\\\" text\");" }

Or:

import string
import json
import functools

quote_swap = functools.partial(
    string.translate, table=string.maketrans('\'"', '"\'')
)

def encode_single_quoted_js_string(s):
    return quote_swap(json.dumps(quote_swap(s)))
like image 130
Eric Avatar answered Oct 11 '22 12:10

Eric