diff --git a/Tests/OutputFilterTest.php b/Tests/OutputFilterTest.php index acab4710..f173d079 100644 --- a/Tests/OutputFilterTest.php +++ b/Tests/OutputFilterTest.php @@ -102,6 +102,18 @@ public function testLinkXhtmlSafe() ); } + /** + * Tests making strings safe for usage in JS + */ + public function testStringJSSafe() + { + $this->assertEquals( + '\u0054\u0065\u0073\u0074\u0020\u0073\u0074\u0072\u0069\u006e\u0067\u0020\u0045\u0073\u0070\u0061\u00f1\u006f\u006c\u0020\u0420\u0443\u0441\u0441\u043a\u0438\u0439\u0020\ud55c\uad6d\uc5b4\u0020\u{1f910}', + $this->object->stringJSSafe('Test string Español Русский 한국어 🤐'), + 'Should convert the string to unicode escaped string' + ); + } + /** * Tests filtering strings down to ASCII-7 lowercase URL text */ diff --git a/src/OutputFilter.php b/src/OutputFilter.php index 51a82976..b65ae1bc 100644 --- a/src/OutputFilter.php +++ b/src/OutputFilter.php @@ -84,6 +84,33 @@ function ($m) { ); } + /** + * Processes a string and escapes it for use in JavaScript + * + * @param string $string String to process + * + * @return string Processed text + * + * @since 3.0 + */ + 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; + } + /** * Generates a URL safe version of the specified string with language transliteration. *