/** * Returns an escaped string suitable for use within a javascript string * * for e.g.: * let foo = "foo <?= $e->js('bar "bar" bar') ?>"; * * will become: * let foo = "foo bar \"bar\" bar"; */ public function js($string) { if ($string === '' || $string === false || $string === null) { return ""; } // this also applies __toString() $string = (string) $string; if (is_string($string)) { $encoded = substr($this->jsonEncode($string), 1, -1); // json_encode only escapes double-quotes. escape singles by hand instead // of JSON_HEX_APOS in case old handsets don't like \u0027 (still need to // verify) return strtr($encoded, ["'" => "\\'"]); } throw new \InvalidArgumentException("String or number required. Found: " . \DebugHelper::getType($string)); }