repr works quite well, and I've used it with lots of different javascript... However I'm not completely confident in it as it fails for unicode.
eg. >>> a = u'a=\'asdfd\';\n\r\n' >>> a u"a='asdfd';\n\r\n" >>> print repr(a) u"a='asdfd';\n\r\n" This is an invalid js string. eek. So first we need to translate it to the correct charset encoding for the document. However js and python encoding of unicode in strings is different too. Here is one below which kind of works for js unicode stuff. But not correctly, and the output isn't the best(too many backslashes), and it isn't the fastest. def encode_js(text, charset = None): if type(text)==type(u""): text= text.encode([charset, 'utf-8'][charset==None]) text = text.replace("\r", "\\r").replace("\n", "\\n") text = text.replace('"', '\\"').replace("'", "\\'") return "'" + text + "'" This would be a good function to get right. We need the specifications, as well as unittests first :) On 4/26/05, Shannon -jj Behrens <[EMAIL PROTECTED]> wrote: > Hey guys, > > I need a JavaScript escape function. Let's say I have a variable, and > I'm generating some JavaScript from Cheetah: > > var s = "$s"; > > I need to make $s safe: > > var s = "$javascript_safe($s)"; > > Has anyone coded this yet? Will the same function work for both > single and double quoted strings? Can I steal some code? > > Thanks :-D > -jj > > -- > I have decided to switch to Gmail, but messages to my Yahoo account will > still get through. > _______________________________________________ > Web-SIG mailing list > Web-SIG@python.org > Web SIG: http://www.python.org/sigs/web-sig > Unsubscribe: http://mail.python.org/mailman/options/web-sig/renesd%40gmail.com > _______________________________________________ Web-SIG mailing list Web-SIG@python.org Web SIG: http://www.python.org/sigs/web-sig Unsubscribe: http://mail.python.org/mailman/options/web-sig/archive%40mail-archive.com