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

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>

Related

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);

How to replace string with the main string with javascript

Trying to do something like making html codes usable in my forum. I want to make text hidden when wrapped with the [hidden] string and after clicking on a button the original text between the [hidden] and [/hidden] tags should be shown. I try using
var res = str.replace("[hidden]$1[/hidden]", "$1");
You need to escape the brackets, [], otherwise they will be interpreted as a character set.
var string = '[hidden]test[/hidden]';
string = string.replace(/\[hidden\](.*?)\[\/hidden\]/g, '$1');
// "test"

Javascript regex not containing keyword with backslashes

I'm having a problem with a javascript regex that has to comment out all tags inside a script tag. But it can not comment out special first script tag with id "ignorescript".
Here is a sample string to regex:
<script id="ignorescript">
var test = '<script>test<\/script>;
var xxxx = 'x';
</script>
Script tag inside ignorescipt has extra backslash because it is JSON encoded (from PHP).
And here is the final result i have to get:
<script id="ignorescript">
var test = '<!ignore-- <script>test<\/script> ignore-->;
var xxxx = 'x';
</script>
Following example works:
content = content.replace(/(<script>.*<\\\/script>)/g,
"<!--ignore $1 ignore-->");
But I need to check that it does not contain a keyword "ignorescript". If that keyword comes up then I do not want to replace anything. Otherwise add ignore comments to whole script tag So far I have gotten this far:
content = content.replace(/(<script.((?!ignorescript).)*<\/script>)/g,
"<!--ignore $1 ignore-->");
It kinda works, but not the way it supposed to be. I also have one more backslash in ending tag. So I changed it to:
content = content.replace(/(<script.((?!ignorescript).)*<\\\/script>)/g,
"<!--ignore $1 ignore-->");
Not it does not find anything at all.
Got it finally working.
Here is the working regex:
/(<script(?!\sid="ignorescript").*?<\\\/script>)/g

How do I replace line breaks?

I am trying to replace line breaks with a comma in javascript but the code doesn't seem to work.
var data = "Series
Manga
Games
Artbooks
Visual Novels"
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);
here you can see a online version http://jsfiddle.net/CBvpS/
Anyone know how to fix it?
Works great when your input string is syntactically correct:
var data = "Series\nManga\nGames\nArtbooks\nVisual Novels"
var output = data.replace(/\r?\n/gm,",");
alert(output);
http://jsfiddle.net/7V8rg/1/
Javascript does not have multi-line variables like php does, unless you manually escape(\) the end of the line. Further, this does not count as a line-break, so you would have to insert \ns to fix that as well. Otherwise, your code works fine, albeit with some minor modifications.
var data = "Series\n \
Manga\n \
Games\n \
Artbooks\n \
Visual Novels";
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);
Take note, however, if your data is from example, an input text area, you do of course not need to worry about escaping the end of the line, and it will handle the data as it should.
JavaScript doesn't allow you to continue a string with new lines unless you add a backslash at the end of the line. For example:
var string = "a \
string is \
here";
With that being said, if you retrieved some text from a different source and wanted to replace the new lines, something like this should be all you need:
string = string.replace(/\n/g, ',');

Categories

Resources