[Web-SIG] JavaScript escape function

Shannon -jj Behrens jjinux at gmail.com
Tue Apr 26 08:22:57 CEST 2005


> Quoting is so difficult to get right that if many people reimplement
> quoting, some of the implementations are sure to be wrong simply because
> there are so many corner cases. It seems like this might be one area where
> it would be both beneficial and possible to share code between Python web
> frameworks.

Well, I'm sure someone will come along and out do me, but how about
the following:

def javaScriptEscape(s):
    """Prepare ``s`` for use in a JavaScript quoted string.

    Both ``"`` and ``'`` are escaped, so you can use the return value in
    either single or double quotes.

    """
    if not isinstance(s, unicode):
        s = str(s)                  # Never call str on unicode.
    s = "\"'" + s                   # Force repr to use single quotes.
    s = `s`
    start, end = 4, -1		    # Strip outer quotes and added quotes.
    if s.startswith("u"):           # JS strings are implicitly unicode.
        start += 1
    s = s[start:end]                     
    s = s.replace('"', '\\"')       # Escape double quotes too.
    return s

def javaScriptQuote(s):
    """Escape ``s`` and wrap it in single quotes."""
    return "'%s'" % javaScriptEscape(s)


# Do some testing.
if __name__ == '__main__':
    for (k, v) in [("", ""), 
                   ("a", "a"),
                   ("\t", "\\t"),
                   ("\n", "\\n"),
                   ("'", "\\'"),
                   ('"', '\\"'),
                   ("\377", "\\xff"),
                   ("\xff", "\\xff"),
                   (u"\u1234", "\\u1234")]:
        escaped = javaScriptEscape(k)
        if escaped != v:
            raise AssertionError(
                "javaScriptEscape(%s) led to %s instead of %s" % 
                (`k`, `escaped`, `v`))
    assert javaScriptQuote("foo\n") == "'foo\\n'"

Note, I purposely chose to have two separate functions, because I
sometimes want one, and I sometimes want the other.

If anyone wants this code, please consider it in the public domain. 
On the other hand, I wouldn't mind being included in your CONTRIB. 
Thanks!

Best Regards,
-jj

-- 
I have decided to switch to Gmail, but messages to my Yahoo account will
still get through.


More information about the Web-SIG mailing list