This question already has answers here:
javascript Syntax error : Unterminated string literal [duplicate]
(3 answers)
Closed 9 years ago.
I am trying to debug a JavaScript script that gets read in a Firefox extension and executed. I only can see errors via the Firebug console (my code is invisible to Firebug), and it's reporting a "unterminated string literal."
I checked the line and the lines around it and everything seems fine-parentheses, braces, and quotes are balanced, etc. What are other possible causes that I should be looking for?
Most browsers seem to have problems with code like this:
var foo = "</script>";
In Firefox, Opera and IE8 this results in an unterminated string literal error. Can be pretty nasty when serializing html code which includes scripts.
Look for linebreaks! Those are often the cause.
I would vote for jamtoday's answer if I had the "reputation"
If your data is coming by way of PHP, this might help
$str = str_replace(array("\r", "\n"), '', $str);
I just discovered that "<\/script>" appears to work as well as "</scr"+"ipt>".
Just escape your tag closures or use ascii code
ie
<\/script>
ie
</script>
You might try running the script through JSLint.
Look for a string which contains an unescaped single qoute that may be inserted by some server side code.
If you've done any cut/paste: some online syntax highlighters will mangle single and double quotes, turning them into formatted quote pairs (matched opening and closing pairs). (tho i can't find any examples right now)... So that entails hitting Command-+ a few times and staring at your quote characters
Try a different font? also, different editors and IDEs use different tokenizers and highlight rules, and JS is one of more dynamic languages to parse, so try opening the file in emacs, vim, gedit (with JS plugins)... If you get lucky, one of them will show a long purple string running through the end of file.
Have you escaped your forward slashes( / )?
I've had trouble with those before
I've had trouble with angled quotes in the past ( ‘ ) usually from copy and pasting from Word. Replacing them with regular single quotes ( ' ) does the trick.
Also, keep in mind that %0A is the linefeed character URL encoded. It took me awhile to find where there was a linefeed in my offending code.
If nothing helps, look for some uni-code characters like
\u2028
this may break your string on more than one line and throw this error
Maybe it's because you have a line break in your PHP code. If you need line breaks in your alert window message, include it as an escaped syntax at the end of each line in your PHP code. I usually do it the following way:
$message = 'line 1.\\n';
$message .= 'line 2.';
Have you tried Chromebug? It's the Firebug for extensions.
Try a "binary search". Delete half the code and try again. If the error is still there, delete half the remaining code. If the error is not there, put what you deleted back in, and delete half of that. Repeat.
You should be able to narrow it down to a few line fairly quickly. My experience has been that at this point, you will notice some stupid malformed string.
It may be expedient to perform this on a saved version of the HTML output to the browser, if you're not sure which server-side resource the error is in.
The web page developer guessed wrong about which encoding is used by the viewer's browser. This can usually be solved by specifying an encoding in the page's header.
Scan the code that comes before the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.
Whitespace is another issue I find, causes this error. Using a function to trim the whitespace may help.
str = str_replace(array("\r\n","\n\r","\r", "\n"), '<br />', stripslashes($str));
This should work.
Related
Long story short, I'm trying to "fix" my system so I'm using the same regular expressions on the backend as we are the front (validating both sides for obvious security reasons). I've got my regex server side working just fine, but getting it down to the client is a pain. My quickest thought was to simply store it in a data attribute on a tag, grab it, and then validate against it.
Well, me, think again! JS is throwing me for a loop because apparently RegExp interprets the string differently depending how it's pulled in. Can anyone shine some light on what is happening here or how I might go about resolving this issue
HTML
<span data-regex="(^\\d{5}$)|(^\\d{5}-\\d{4}$)"></span>
Javascript
new RegExp($0.dataset.regex)
//returns /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/
new RegExp($($0).data('regex'))
//returns /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/
new RegExp("(^\\d{5}$)|(^\\d{5}-\\d{4}$)");
//returns /(^\d{5}$)|(^\d{5}-\d{4}$)/
Note in the first two how if I pull the value from the data attribute dynamically, the constructor for RegExp for some reason doesn't interpret the double slash correctly. If, however, I copy and paste the value as a string and call RegExp on the value, it correctly interprets the double slash and returns it in the right pattern.
I've also attempted simply not escaping the \d character by double slashing on the server side, but as you might (or might not) have guessed, the opposite happens. When pulled from attributes/dataset, the \ is completely removed leading the Regex to think I'm looking for the "d" character rather than digits. I'm at a loss for understanding what JS is thinking here. Please send help, Internet
Your data attribute has redundant backslashes. There's no need to escape backslashes in HTML attributes, so you'll actually get a double-backslash where you don't want one. When writing regular expressions as strings in JavaScript you have to escape backslashes, of course.
So you don't actually have the same string on both sides, simply because escaping works differently.
In my web application (JSP, JQuery...) there is a form which, along with other fields, has a textarea where the user can input notes freely. The value is saved to the database as is.
The problem happens when the value has newline characters and is loaded back to the textarea; it sometimes "breaks" the Jquery code. Explaining further:
The value is loaded to the textarea using Jquery:
$('#p_notas').text("value_from_db");
When the user hits Enter to insert a new paragraph, the resulting value will include a newline character (or more than one char). This char is the problem as it varies from browser to browser and I haven't found out which one is causing the problem.
The error I get is a console error: SyntaxError: unterminated string literal. The page doesn't load correctly.
I'm not able to reproduce the problem. I tried with Chrome, Firefox and IE Edge (with several combinations of user agent and document mode).
We advise our users to use IE8+, Firefox or Chrome but we can't control it.
What I wanted to know is which character is causing the problem and how can I solve it.
Thanks
EDIT: Summing up - What are the differences in newline characters for the different browsers? Can I do anything to make them uniform?
EDIT 2: Looking at the page in the debugger, what I get is:
Case 1 (No problem)
$('#p_notas').text("This is the text I inserted \r\n More text");
Case 2 (Problem)
$('#p_notas').text("This is the text I inserted
More text");
In case 2 I get the Javascript error "SyntaxError: unterminated string literal." because it is interpreted as two lines of code
EDIT 3: #m02ph3u5 I tried using '\r' '\n' '\r\n' '\n\r' and I couldn't reproduce the problem.
EDIT 4: I'm going to try and replace all line breaks with '\n\r'
EDIT 5: In case it is of interest, what I did was treat the value before it was saved
value.replace(/(?:\r\n|\r(?=\n)|\n(?=\r))/g, '\n\r')
The problem isn't the browser but the operating system. Quoting from this post:
So, using \r\n will ensure linebreaks on all major operating systems
without issue.
Here's a nice read on the why: why do operating systems implement line breaks differently?
The problem you might be experiencing is saving the value of the textarea and then returning that value including any newlines. What you could do is "normalize" the value before saving, so that you don't have to change the output. In other words: get the value from the textarea, do a find-and-replace and replace every ossible occurrence of a newline (\r, \n) by a value that works on all OS's \r\n. Then, when you get the value from the database later on, it'll always be correct.
I suspect your problem is actually any new line in the entered input is causing an issue. It looks like on the server you are have a templated page something like:
$('#p_notas').text("<%=db.value%>");
So what you end up with client side is:
$('#p_notas').text("some notes that
were entered by the user");
or some other characters that break the JS. Embedded quotes would do it too.
You need to escape the user entered values some how. The preferred "modern" way is to format info you are returning as AJAX. If you are embedding the value within a template what I might do is:
<div style="display:none" id="userdata><%=db.value%></div>
<script>$('#p_notas').text($("#userdata").text());</script>
Of course if it were this exactly you could just embed the data in the text area <textarea><%=db.value%></textarea>
When you output data to the response, you always need to encode it using the appropriate encoding for the context it appears in.
You haven't mentioned which server-side technology you're using. In ASP.NET, for example, the HttpUtility class contains various encoding methods for different contexts:
HtmlEncode for general HTML output;
HtmlAttributeEncode for HTML attributes;
JavaScriptStringEncode for javascript strings;
UrlEncode for values passed in the query-string of a URL;
In some cases, you might need to encode the value more than once. For example, if you're passing a value in a URL via a javascript string, you'd need to UrlEncode the raw value, then JavaScriptStringEncode the result.
Assuming that you're using ASP.NET, and your code currently looks something like this:
$('#p_notas').text("<%# Eval("SomeField") %>");
change it to:
$('#p_notas').text("<%# HttpUtility.JavaScriptStringEncode(Eval("SomeField", "{0}")) %>");
I'm currently working on a website that has two versions, one American website that's served as utf-8 and one Japanese version that's served as Shift JIS. The site is generated using Perl.
The problem:
I'm serving Javascript akin to the following.
var text = "test \"quote\"";
Which, on the Japanese site, is returning an error "Uncaught SyntaxError: Unexpected identifier." This is because the backslash is being converted to an elongated backslash character \, which isn't seen as an escape character and thus is breaking the line.
I can't seem to find anyone else running into this problem which makes me suspicious that there isn't something fundamentally wrong with our website. Has anyone encountered a similar situation and found a solution?
Many thanks
I found some helpful information here:
Why browser is showing different back slash for a email validation regex. How to prevent that?
Which lead me to this upsetting hack:
var text = "test ¥"quote¥"";
This works perfectly. Now, obviously this isn't the way to do it, but it will enable other devs to get on testing other JS interactions on the site while I concentrate on refactoring this code into something that doesn't rely on character escaping. I hope this information helps someone else at some point!
I am experiencing a classic JS case (in my opinion) but after a lot of googling, still not able to find a solution. Backslash is considered as a escape character in JS but what you do when you need to pass windows path from the JS and print it?
I am using eval because my java applet is executing the code and placing bits when it has a string to evaluate. That's why eval is necessary, however I have made an example which is below:
<div id="mainTabs"></div>
<script>
var s = "document.getElementById('mainTabs').innerHTML='\\C\ganye\file.doc'";
eval(s);
</script>
I tried double backslashes, not working, if anyone could help me get around this with as less hassle as possible, I will feel grateful.
Because you're using eval, the Javascript interpreter is getting invoked twice - so you need quadruple backslashes, not double:
var s = "document.getElementById('mainTabs').innerHTML='\\\\\\\\C\\\\ganye\\\\file.doc'";
This results in s getting set to:
document.getElementById('mainTabs').innerHTML='\\\\C\\ganye\\file.doc'
so the innerHTML gets set to:
\\C\ganye\file.doc
which is what you wanted. (I'm not sure I understand your reasons for needing eval(), but this is how to work around the problem if you do :-)
You need to quadruple the backslashes, because the the string literal is first interpreted by the JS parser, and then the result is again parsed due to the eval call.
Or, preferably, try to avoid using eval. It is almost never necessary and it adds complication and slows down execution.
This example would work as just:
document.getElementById('mainTabs').innerHTML='\\C\ganye\file.doc';
I went to http://www.json.org/js.html and downloaded the json2.js, thinking i'd be fine, afterall that site is on the top in a google search for 'json javascript' - also they have this really cool url :)
So i've been working a bit with it and it seemed fine, but now i start running into trouble with it - it simply won't parse certain stuff i encode with Newtonsoft's JSON .NET serializer. Ok so perhaps the .net seralizer messes up? Not how i see it - it produces a fine javascript string that looks like perfect json.
The problem comes when it has to encode a single quote ' and perhaps double quotes ".
Take a look at these examples (only parts of the full string)
{"Id":10651,"Text":"\'69"}
{"Id":184,"Text":"13\""}
Am I missing something? it's part of a bigger string and all put in a javascript variable like this
var jsonObject = '[{"Id":46,"Type":2,.....................
I'm thinking it has to escape the singlequote in the string to avoid conflicting with my wrapping of the string in single quotes, and escape the double quote to avoid conflicting with the json format?
So either i'm doing something wrong or the json2.js is not doing it right? Or yeah perhaps the .net json is messing up - i'm kinda thinking i'm messing it up, but i've been trying to do all sorts of stuff to help with the parsing like escaping/unescaping etc. before the serializing/deserializing.
Ok i solved the problem. Actually the hint Joel gave me in the comment on my question to try and eval it instead lead me to thinking i can trust this json i'm trying to parse/eval, and since i know it at the time of building the page, why not hardcode it into the webpage AS an object - no escaping of quotes or anything and no evaluating and best of all - no strings :P
So thanks to both you Joel and you torial :)
This may be a lead...
http://binnyva.blogspot.com/2006/10/invalid-json.html
And if you are serializing, perhaps protect yourself by serializing to ' and from '.