2

I want to use python to generate javascript code dynamiclly.

def convert(jsstring=''):
    return 'function dosomething () { return %s.toLowerCase(); }' % jsstring

The problem is jsstring is a python string.

How can i convert it back to javascript string literal to make dosomething a valid javascript function ?

for example

call

convert("javascript")

now output

 function dosomething () { return javascript.toLowerCase(); }

which is not a valid javascript function

expected output

 function dosomething () { return "javascript".toLowerCase(); }

another example, call

convert("javascript\'")

expected output

 function dosomething () { return "javascript\'".toLowerCase(); }

Thanks a lot.

1
  • what is "python string lexical"? Commented May 1, 2012 at 8:36

6 Answers 6

3

You want json:

import json

jsstring = """
    foo "bar"
"""

print 'function dosomething () { return %s.toLowerCase(); }' % json.dumps(jsstring)

Suggested repr won't work with unicode strings:

jsstring = u"\u1234"
print 'function dosomething () { return %s.toLowerCase(); }' % repr(jsstring) 

returns

function dosomething () { return u'\u1234'.toLowerCase(); }

which is not valid javascript.

Sign up to request clarification or add additional context in comments.

2 Comments

Using json here just for string quoting is a bit of an overkill.
@CiroSantilli: json.dumps uses ensure_ascii=True by default, so weird unicodes are not an issue.
2

How about adding appropriate quotes around %s, i.e.:

'function dosomething () { return "%s".toLowerCase(); }' % jsstring

Here's a command-line session to clarify the difference:

In [10]: joe = 'somestring'

In [11]: '%s.toLowerCase();' % joe
Out[11]: 'somestring.toLowerCase();'

In [12]: '"%s".toLowerCase();' % joe
Out[12]: '"somestring".toLowerCase();'

1 Comment

not that simple. how about convert("javascript\'"). the return will be 'javascript ''.toLowerCase(); it illegal in javascript
2

Step through your code:

def convert(jsstring=''):
    return 'function dosomething () { return %s.toLowerCase(); }' % jsstring

Now, if jsstring is "Foo", what does it produce?

function dosomething () { return Foo.toLowerCase(); }

Of course this will fail. There is no variable called Foo set in the javascript function.

In all likelihood, you wanted a string literal:

def convert(jsstring=''):
    return 'function dosomething () { return "%s".toLowerCase(); }' % jsstring

Of course, you'll need to make sure nothing goes wrong if jsstring includes quotes, linebreaks and other sensitive characters. I'll leave that to you.

1 Comment

should get them on the right track. Don't have unlimited time.
2

Use repr inside string interpolation:

>>> 'This is a string: %r' % ('python string')
'This is a string: "python string"'

So just replace %s with %r in your code. repr() will do the work for you.

Comments

1

Use repr, or else your string will not work if it contains " or '. For example:

... % repr(jsstring)

Failure to use repr may also be a security vulnerability (via injection of " or ' or other characters). Failure to use repr may also cause your javascript to fail if your string contains those characters. Though if security is a concern, you will also want to avoid text like </script>, and other things, by putting it through a proper escaping system, or encode it in something like base64.

Comments

1

You better quote the string appropriately what ever you are passing to the function. This will keep things simple

For the example mentioned

>>> convert('"javascript"')
'function dosomething () { return "javascript".toLowerCase(); }'

And if you want to pass a quoted string, escape it appropiately

>>> print convert("\"javascript\"\"")
function dosomething () { return "javascript"".toLowerCase(); }

And remember if you want the raw representation, always use repr, you will get what you are intending

>>> repr(convert("\"javascript\"\""))
'\'function dosomething () { return "javascript"".toLowerCase(); }\''

or to keep it transparent, add the repr inside the function.

>>> def convert(jsstring=''):
    return repr('function dosomething () { return %s.toLowerCase(); }' % jsstring)

>>> convert("\"javascript\"\"")
'\'function dosomething () { return "javascript"".toLowerCase(); }\''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.