[Web-SIG] JavaScript escape function

Donovan Preston dp at ulaluma.com
Tue Apr 26 04:26:39 CEST 2005


On Apr 26, 2005, at 1:19 AM, Jp Calderone wrote:

>
>  Nevow has liveevil.jquote(), which I believe does what you want.   
> It is strikingly simple and straightforward:
>
>    def jquote(jscript):
>        return jscript.replace('\\', '\\\\'
>            ).replace("'", "\\'"
>            ).replace('\n', '\\n')
>
>  I wonder if it isn't buggy somehow :)  I don't know javascript  
> well enough myself to say either way.

This is for explicitly quoting strings for inclusion in a javascript  
function call which is being built, which is why it is quoting '

For example:

nevow_clientToServerEvent('identifier', 'hello(\'world\')')

The second argument would have been a python string which looked like  
this, which was then run through jquote before being used to build  
the nevow_clientToServerEvent call:

"hello('world')"

To apply this to jj's original example, assigning a javascript string  
to a javascript variable, use single quotes around the call to  
jquote, or switch jquote to quote " instead of '

var s = '$jquote($s)'

Leaving it up to the developer to ensure every potentially unsafe  
python string is quoted properly always makes me nervous. Nevow has  
enough information to automatically safely quote strings inserted in  
html, html attribute, and URL contexts, but isn't currently smart  
enough to know much about javascript and javascript string quoting  
contexts. livepage will try to quote things properly for you if you  
are using livepage.handler (which uses jquote as shown above) but  
it's pretty easy to fool, because nevow doesn't yet know enough about  
JavaScript to really be safe. I hope to add some additional  
intelligence soon to cover this, and perhaps also to cover CSS contexts.

dp



More information about the Web-SIG mailing list