public static function js($string)
    {
        // escape all non-alphanumeric characters
        // into their \xHH or \uHHHH representations
        $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) {
            $char = $matches[0];
            // \xHH
            if (!isset($char[1])) {
                return '\\x' . strtoupper(substr('00' . bin2hex($char), -2));
            }
            // \uHHHH
            $char = iconv('UTF-8', 'UTF-16BE', $char);
            return '\\u' . strtoupper(substr('0000'.bin2hex($char), -4));
        }, $string);

        return $string;
    }
public static function js($string)
    {
        // escape all non-alphanumeric characters
        // into their \xHH or \uHHHH representations
        $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) {
            $char = $matches[0];
            // \xHH
            if (!isset($char[1])) {
                return '\\x' . strtoupper(substr('00' . bin2hex($char), -2));
            }
            // \uHHHH
            $char = iconv('UTF-8', 'UTF-16BE', $char);
            return '\\u' . strtoupper(substr('0000'.bin2hex($char), -4));
        }, $string);

        return $string;
    }
public static function js ( $ string ) { // escape all non-alphanumeric characters // into their \xHH or \uHHHH representations $ string = preg_replace_callback ( '#[^a-zA-Z0-9,\._]#Su' , function ( $ matches ) { $ char = $ matches [ 0 ] ; // \xHH if ( ! isset ( $ char [ 1 ] ) ) { return '\\x' . strtoupper ( substr ( '00' . bin2hex ( $ char ) , - 2 ) ) ; } // \uHHHH $ char = iconv ( 'UTF-8' , 'UTF-16BE' , $ char ) ; return '\\u' . strtoupper ( substr ( '0000' . bin2hex ( $ char ) , - 4 ) ) ; } , $ string ) ; return $ string ; }
Escapes untrusted data for inserting into javascript variable, function parameter

<script>var currentValue='UNTRUSTED DATA';</script>
<script>someFunction('UNTRUSTED DATA');</script>

Per QWASP:
The only safe place to put untrusted data into this code is inside a quoted "data value".
Including untrusted data inside any other JavaScript context is quite dangerous,
as it is extremely easy to switch into an execution context with characters including (but not limited to)
semi-colon, equals, space, plus, and many more, so use with caution.

Please note there are some JavaScript functions
that can never safely use untrusted data as input - EVEN IF JAVASCRIPT ESCAPED!

<script>
window.setInterval('...EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE...');
</script>

Except for alphanumeric characters, escape all characters with the \uXXXX unicode escaping format (X = Integer).

@param string $string Untrusted data

@return string Escaped data
Escapes untrusted data for inserting into javascript variable function parameter