new line text causing error in javascript 'unterminated string literal' - javascript

I am working with laravel, I have string like this in database,
hello
username, address
country
Username and country is in new line, and fields type is 'text' in database,
When i am trying to get that into JavaScript variable like this,
var add="{{ $data['order']->address }}";
Getting error unterminated string literal. No error if string in 1 line in database.

First option
You can use ES6 and the new string notation:
var str = `my
multiline
string`;
Second option
Replace newlines with \n as described here:
var add="<?=str_replace("\n", '\n', $data['order']->address)?>"

Related

Detect line breaks (\n) while reading from a database (Javascript, HTML, firebase)

I'm trying to use a string retrieved from firebase firestore and display it on my HTML page with line breaks.
In the store, I have a string that looks like this
row1\nrow2\nrow3
When I retrieve it and try to add it to my page the \n's do not register as line breaks. I am using pre-wrap and using a test-string works fine.
let text = getString(); //retrieves a string from firebase
document.getElementById('textBox').textContent = text;
Shows this on my page:
row1\nrow2\nrow3
The following test code:
let text = 'row1\nrow2\nrow3';
document.getElementById('textBox').textContent = text;
Shows the following on the page:
row1
row2
row3
So it seems like the \n's in the string retrieved from the database are not read the same way as the \n's that are put inside the string defined directly in the Javascript code. Any idea why? And what can I do to make it read the line breaks?
Similar to what #user14063792468 said in their comment, it appears your newline characters have been escaped (i.e., converts \n to \\n) when a string is stored, so I'd try to replace any instances of \\n with \n (single backslash) and see if that works.
Here's an example of how this might look before and after the replacement:
let string = 'Newline characters\\nare in this\\nstring\\nfor sure'; // note the double slashes
document.getElementById('before').textContent = string;
let text = string.replace(/\\n/g, "\n");
document.getElementById('after').textContent = text;
<pre id="before"></pre>
<pre id="after"></pre>

Break out from JavaScript variable

So, I have the following code:
<script type="text/javascript">
var name = prompt("What's your name?");
var greeting = "Hello " + name + " :D";
console.log(greeting);
</script>
I am trying to break out from name variable. For example: answering the question by
"alert(1);\\
In browser console, printing name variable shows the following:
Now, when trying to create a second variable with the same content it produces an error.
Why does "name" contain invalid syntax content? and is there any way to break out from the variable in this scenario?
When you input "alert(1);\\ in the prompt, the special characters are automatically escaped and the input is assigned to name, but when you are doing that via the console or a script, you have to escape the characters manually. Since you wrote the string using double-quotes, the correct way to do the assignment would be:
var test = "\"alert(1);\\\\";
When uing single-quotes, you wouldn't have to escape the double-quotes:
var test = '"alert(1);\\\\';
What I did here is escape the required characters by putting a \ before them. What you see when you try to view the value of name is the actual content without the escaping.
JavaScript believes that you are ending the string literal at the second quotation mark.
Two possible solutions:
Wrap with single quotes: test = '"alert(1)\\'
Escape the second quote: test = "\"alert//"

Firestore won't read \n on a jspdf string

I'm trying to get a new line on a jspdf string. Problem is firestore won't recognize it ( \n ) as a line break but as a string.
Solutions I've tried:
\n\n , html br tag
var string = "This is a sample lb\n text"
var string1 = string.replace("lb","\n")
doc.text(10,10, string1)
actual : This is a sample lb\n text
expected : This is a sample
text
The Cloud Firestore SDKs don't have an issue with new lines, so the issue must be somewhere else in your code. To demonstrate, I ran the below code that wrote a string into a document, retrieved it, then displayed the result:
Code:
db = firebase.firestore();
db.collection("lines").doc("newline").set({'myString': "This is a new\nline"});
x = db.collection("lines").doc("newline").get();
x.then(function(doc) {console.log(doc.data().myString)});

Parse JSON but preserve \n in strings

I have this JSON string:
{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}
I can parse it when I do this:
pg = JSON.parse(myJSONString.replace(/\\/g, ""));
But when I access pg.text the value is:
Line 1nLine 2.
But I want the value to be exactly:
Line 1\nLine 2
The JSON string is valid in terms of the target program which interprets it as part of a larger command. It's Minecraft actually. Minecraft will render this as you would expect with Line 1 and Line 2 on separate lines.
But I'm making a editor that needs to read the \n back in as is. Which will be displayed in an html input field.
Just as some context here is the full command which contains some JSON code.
/summon zombie ~ ~1 ~ {HandItems:[{id:"minecraft:written_book",Count:1b,tag:{title‌​:"",author:"",pages:‌​["{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}"]}},{}]}
Try adding [1] at /\[1]/g but works for single slash only, but since the type of the quoted json i think is a string when you parse that it slash will automatically be removed so you don't even need to use replace. and \n will remain as.
var myString ='{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}';
console.log(JSON.parse(myString.replace(/\\[1]/g, ""))); //adding [1] will remove single slash \\n -> \n
var myString =JSON.parse(myString.replace(/\\[1]/g, ""));
console.log(myString.text);
Your string is not valid JSON, and ideally you should fix the code that generates it, or contact the provider of it.
If the issue is that there is always one backslash too many, then you could do this:
// Need to escape the backslashes in this string literal to get the actual input:
var myJSONString = '{\\"text\\":\\"Line 1\\\\nLine 2\\",\\"color\\":\\"black\\"}';
console.log(myJSONString);
// Only replace backslashes that are not preceded by another:
var fixedJSON = myJSONString.replace(/([^\\])\\/g, "$1");
console.log(fixedJSON);
var pg = JSON.parse(fixedJSON);
console.log(pg);

JavaScript/<text area >

alert("...");
var values = "value1
valu2part1 value2part2
value3
valu4";
alert(values);
I am assigning:
var values = "<%=Model.Values%>";
These values are stored in a database. The values are entered through a textarea
and in the database each line is seperated by \t\r.
When I take this to a JavaScript variable using:
var values = "<%=Model.Values%>";
I am getting some thing like:
var values = "value1
valu2part1 value2part2
value3
valu4";
But this is anerror. What can I do?
var values = "<%=Model.Values%>";
This is unsafe. Not only will it fail when there are newlines in the string (as JavaScript string literals cannot span multiple lines), it's also possible for a " in the value to end the string prematurely. If the value contains user-submitted data, that's a script-injection security hole (XSS).
To create JS literal syntax use a JSON serialiser. For example with JavaScriptSerializer:
var values= <%= new JavaScriptSerializer().Serialize(Model.Values) %>;
or eg Json.NET if you're on older .NET versions.
You can replace your new lines with escape sequences (\n) before outputting your string to the JS.

Categories

Resources