What is the best way to escape JavaScript data?

The PEAR JavaScript package does this:

 function escapeString($str)  {
        $js_escape = array(
            "\r"    => '\r',
            "\n"    => '\n',
            "\t"    => '\t',
            "'"     => "\\'",
            '"'     => '\"',
            '\\' => '\\\\'
        );
        return strtr($str,$js_escape);
    }

I also found this, which converts every character to its code ‹ pretty
extreme.

function javascript_escape($str) {
    $new_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $new_str .= '\x' . dechex(ord(substr($str, $i, 1)));
    }
    return $new_str;
}

Thoughts?

Cliff
_______________________________________________
New York PHP Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk

NYPHPCon 2006 Presentations Online
http://www.nyphpcon.com

Show Your Participation in New York PHP
http://www.nyphp.org/show_participation.php

Reply via email to