1. Introduction
In JavaScript, when you define a large string, especially if there is a line break, in order to look neat and readable, you generally use a continuation character, for example:
var script = "var chart = Anychart.piechart ([[' Chocolate Paste ', 5], [' White Honey ', 2], [' Strawberry jam ', 2 ], [' сondensed milk ', 1] ]);//chart.bounds (0, 0, 100%,100%); var stage = anychart.graphics.create (' container ', (a); Stage.container (' container '); Chart.container (stage). Draw (); ";
2. Questions
If we take this code directly, we will find that the result is quite different from the original expectation.
3, problem analysis
Because, as a script, a continuation character is used only to guarantee the continuity and legality of the string (stating that this is a complete string), but the newline character is not included in the string. That is, in the above code, the script string will not contain a newline character. This is a very serious problem, if the string is script code, and contains the line comment ("//"), it will change the original logic, the code after the line comment will be commented out, will not be executed.
For example, the following example encodes the script code and then sends it to the background execution (as in node. js), where it is simple to decode:
<textarea id= "textarea1" rows= "All" cols= "" ></textarea><script lang= "javascript" >var script = "var Chart = Anychart.piechart ([' chocolate Paste ', 5], [' White Honey ', 2], [' Strawberry Jam ', 2], [' Сondensed milk ', 1] ]);//chart.bounds (0, 0, 100%,100%); var stage = anychart.graphics.create (' container ', 600, 400); stage.container (' container '); Chart.container (stage). Draw (); "; var script_out = encodeuricomponent (script); var textarea1 = document.getElementById (' textarea1 '); Textarea1.value = decodeURIComponent (script_out);</script>
Run results
You can see the loss of line breaks in the string script, the code mess, especially
Chart.bounds (0, 0, 100%,100%);
This line is connected to the following line, assuming the code is executed, and the code behind it will not be executed.
4. Solutions
Add a newline character after the code with the line comment, to prevent the subsequent code from being commented out, or to annotate the code with the range comment character (/*/).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
javascript[easy to ignore ERROR]: line break is missing when continuation line encounters newline