Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: unterminated string literal strange error [duplicate]

Tags:

javascript

I have this strange unterminated string literal error in JavaScript. When I output only a single word like "php" (in the cache_open.handler variable). There is no error. This is the script and below works fine:

        <script>
        var cache_open = {};
        var cache_name_open={};         
        var handler='open';
        cache_open.handler='<pre class="brush: html;">php</pre>';           
        cache_name_open.handler='PHP prepared statement';           
        </script>

However when I output a code (html entity outputted source code) to the culprit variable cache_open.handler, it returns unterminated string literal error in the console.

This is the sample output where it returns an error:

        <script>
        var cache_open = {};
        var cache_name_open={};         
        var handler='open';
       cacheObj_open.handler='<pre class="brush: html;">
       &lt;?php
       $stmt = $dbh-&gt;prepare(&quot;SELECT * FROM REGISTRY where name = ?&quot;);
       if ($stmt-&gt;execute(array($_GET['name']))) {
       while ($row = $stmt-&gt;fetch()) {
       print_r($row);
       }
       }
       ?&gt;</pre>';            
    cache_name_open.handler='PHP prepared statement';           
        </script>

At first I thought it was just the complexity of the code returned (for example containing quotes, etc.). But even a simple HTML code also returns an error:

        <script>
        var cache_open = {};
        var cache_name_open={};         
        var handler='open';
        cacheObj_open.handler='<pre class="brush: html;">&lt;html&gt;
        &lt;body&gt;
        &lt;p&gt;Hello world.&lt;/p&gt;
        &lt;/body&gt;
        &lt;/html&gt;</pre>';           
    cache_name_open.handler='PHP prepared statement';           
        </script>

Any ideas what is causing the error? Any suggestions for modifications is highly appreciated thanks!

like image 548
Emerson Maningo Avatar asked Jan 05 '13 08:01

Emerson Maningo


People also ask

How do you fix unterminated string constant?

To solve the "Unterminated string constant" error, make sure to enclose your strings in quotes consistently. String literals must be enclosed in single quotes, double quotes or backticks. When writing a multiline string use backticks.

What does unterminated string literal mean?

"unterminated string literal" means that somewhere a string variable is opened by not closed properly, either because of un-escaped character in it, or a line break, or something like that.


1 Answers

Javascript strings can't break across newlines without an escape (\). See this question for detailed answers:

  • How do I break a string across more than one line of code in JavaScript?
like image 105
Hamish Avatar answered Oct 26 '22 18:10

Hamish