Whilst “\n” is the normal way of adding a newline to a JavaScript string (or “\r\n”), if you do it inside a php heredoc string, it gets stripped and turned into a newline in the output, so its lost from the JavaScript string and the browser see’s the string continue on a new line causing a JavaScript error.

You can use \\n:

  $HtmlOutput .= <<<_END
    <script>
      const text = "The first line of my string:\\nThe second line of my string";
    </script>
_END;

You can also use fromCharCode to solve this:

  $HtmlOutput .= <<<_END
    <script>
      const text = "The first line of my string:" + String.fromCharCode(10) + "The second line of my string";
    </script>
_END;
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *