Back to OutputFilter class

Method stringJSSafe

public static string
stringJSSafe
(mixed $string)
This method processes a string and escapes it for use in JavaScript
Parameters
  • string $string String to process
Returns
  • string Processed text
Class: OutputFilter
Project: Joomla

Method stringJSSafe - Source code

/**
 * This method processes a string and escapes it for use in JavaScript
 *
 * @param   string  $string  String to process
 *
 * @return  string  Processed text
 */
public static function stringJSSafe($string)
{
    $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
    $new_str = '';
    foreach ($chars as $chr) {
        $code = str_pad(dechex(StringHelper::ord($chr)), 4, '0', STR_PAD_LEFT);
        if (strlen($code) < 5) {
            $new_str .= '\\u' . $code;
        } else {
            $new_str .= '\\u{' . $code . '}';
        }
    }
    return $new_str;
}