New line characters Desktop vs Server - Updated - javascript

I am trying to catch new line characters with JavaScript.But here is the catch.
For example with a string as argument to my function;
s = "some_text_with_a_\n_new_line";
Document.write(s);
It will get detected by my script;
Now if I get my text from a textarea and I press enter to produce a line break. It will get detected and interpreted as \n. Now the texte area and the working script are on my desktop. Window 10.
When i upload it to the server (IIS 7 on windows "Godaddy") its not working anymore so I have try some variant like \r\n , \r non of them work. Actually it dont mater much to me cause all I'm looking for is the escaping .
Here is a piece of script I use to find them:
nex = string.indexOf(tokout[i]); // where tokout = '\n'
spacer = 1; //spacer to escape found token
spc = tokin.length; ///last token
if(tokin[spc-1] === '\n'){ //// spacer to set cursor after token
spacer = 2;
}
BBCode = input.substr(curseur,nex+spacer); // we have bbcode
The script is working on my desktop but on the server I can't get the line break!
How it works:
I get the position of the \n.
Set the position of my cursor right after it.
and what is in BBcode is the line break.
For some reason it only work on my PC not the server. So I'm thinking it has to be the way break line are interpreted by the server!

They are not interpretted as space. They are displayed as space. To display AS IS you could surround with a pre tag. e.g.
document.write('<pre>' + s + '</pre>');
Also, you should be looking for \n not //n
i.e. s.indexOf('\n')
if you are trying to output to a document, you could replace the \n with <br/>
e.g. s.replace(/\n/g, '<br/>')

If you want to see line break in HTML you have to use <br /> HTML tag:
document.write("some_text_with_a_<br />_new_line");
However in javascript \n is a valid line break character. For example when you use console.log or alert you will see 2 lines:
console.log("some_text_with_a_\n_new_line");
alert("some_text_with_a_\n_new_line");

Related

How to add '>' to every new line in a string in javascript?

I have a text area on a UI and I need the user to type in Markdown. I need to make sure that each line they type will start with > as I want to view everything the typed as a blockquote when they preview it.
So for example if they type in:
> some text user <b>typed</b>
another line
When the markdown is rendered, only the fist line is a blockquote. The rest is plain text outside the blockquote.
Is there a way I can check each line and add the > if it is missing.
Things I have tried:
I tried removing all > characters and replacing each \n with a \n>. This however messed up the markdown as the user can also type in <b>bold text</b>.
I have a loop that checks for the > character after every new line. I just don't know how to insert the > if its missing.
Loop code:
var match = /\r|\n/.exec(theString);
if (match) {
if (theString.charAt(match.index)!='>'){
// don't know how to ad the character
}
}
I also though that maybe I can enforce the > in the textarea, but that research got me nowhere. As in, I don't think that is possible.
I also thought, what if the user types multiple >>>>. At that stage I was thinking about it too much and said I'd leave out cases like that as maybe that is the user's intention.
If anyone has any suggestions and/or alternative solutions it would be very much appreciated. Thank you :)
You can use a regular expression to insert > to the beginning of each line, if it doesn't exist:
const input = `> some text user <b>typed</b>
another line
another line 2
> another line 3`;
const output = input.replace(/^(?!>)/gm, '> ');
console.log(output);
The pattern ^(?!>) means: match the beginning of a line, which is not followed by >.
If you only want to insert >s where lines have text already, then also lookahead for non-whitespace in the line:
const input = `> some text user <b>typed</b>
another line
another line 2
> another line 3`;
const output = input.replace(/^(?!>)(?=[^\n]*\S)/gm, '> ');
console.log(output);
I'd go with replace (first thing you tried). In order to insert literal > in HTML, you have to escape it.
Just replace \n with \n> and you're all set.

Printing Javascript Template Strings with Line Breaks

Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?
For instance, when I have the following:
let someVar = 'a';
let tsString = `here goes ${someVar}
some other line
some other line`;
console.log(tsString);
I'd like it to print WITH the linebreaks, not printing the \n's instead.
I think there could be some transformation between template strings and regular strings, but I could not find it.
*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).
I think it may be related to the OS you're using since Windows and Mac have different character lengths for their line endings.
To answer the particular question which seems to work for me.
const os = require('os');
let someVar = 'a';
let tsString = `here goes ${someVar} ${os.EOL} some other line ${os.EOL} some other line`;
console.log(tsString);
You can read about the os middleware on the nodejs docs here: https://nodejs.org/api/os.html#os_os_eol
This seems to be a similar duplicate of: How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?
Another solution besides adding to the string \n, which is the standard solution is as follows:
You've got there a character for new line:
(I cannot paste that character in here as the markdown kills it)
You could capture it in a variable and insert it in a template string:
const newline = tsString[12];
const myString = `Hello ${newline} World!`;
Hope it helps.
You should try replacing the EOL based on where you are taking the content, forms as a standard should support the CRLF \r\n as per the spec (https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4)
Use the following regex to replace all occurences. \n would match EOL and /gm would match all
let someVar = 'a';
let tsString = `here goes ${someVar}
some other line
some other line`;
//For terminal (detects EOL on it's own)
console.log(tsString);
let txtString = tsString.replace(/\n/gm, `\r\n`);
// Works in terminal and in textarea
console.log(txtString);
//For html content, redundant but if it's just html you want!
let htmlString = tsString.replace(/\n/gm, `<br>`);
console.log(htmlString);
You can embed the data inside string like
const myTemplateString = My sample text 1 is ${one}
My second line 2 is ${two}
console.log(myTemplateString) the ES6 will preserve white spaces and hence you can get the required line breaks.
refer this article

Remove invisible carriage return from CSV using javascript

I try to parse a CSV in Google Apps Script (Google Sheets), with the code below:
var file = DriveApp.getFileById('xx');
var blobasstr = file.getBlob().getDataAsString();
var csvData = Utilities.parseCsv(blobasstr);
All works fine except from the fact that there are invisible carriage returns in my CSV within cells, which result in extra rows being created in the middle of cells.
These carriage returns are a result from the fact that the source data contains cells with two address lines (and the carriage return in the middle). When I open the CSV in notepad I have to type my cursor twice to get past this point which strengthens my idea that there is a hidden carriage return there.
Can I use a regex on my blobasstr that removes these invisible carriage returns, but of course keeps the usual carriage returns at the end of each line?
Edit: Thanks for referring to the earlier question. With the regex:
blobasstr.replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r\n(?:\\[\s\S][^'\\]\r\n)*')/g, '\\r\\n');
I am indeed able to remove the 'hidden' returns which is a great start. The thing is that I now end up with the text \r\n in the cells that had a invisible return (instead of the original content of the cell, this is probably caused by the replacement argument '\r\n' Is there an alternative for this that keeps the original content of the cell (of course without the hidden carriage return?) Thanks a lot!
The help is really appreciated!
Chris
notepad expects dos line endings \r\n and doesn't handle unix line endings single \n, i could reproduce behavior with a simple file with \n, the cursor must be typed twice to advance.
Seems Utilities.parseCsv can't handle multiline cells, because can't specify an optional enclosing character like ".
This is what did it for me eventually:
var blobasstr = blobasstr2.replace(/(?=["'])(?:"[^"\]*(?:\[\s\S][^"\]*)*"|'[^'\]\r\n(?:\[\s\S][^'\]\r\n)*')/g, function(match) { return match.replace(/\n/g,"")} );

Using javascript regex to replace a character entity

I have a set of notes which aren't displaying properly. Looking at the source, there is
where the line breaks should be. I want to replace these instances with <br>. I've used a bookmarklet which will work for a plaintext string such as ABC but it won't work for the given string.
For example, this one works fine:
javascript:(function(){var re = new RegExp("ABC", "g"); document.getElementById('my_span').innerHTML=document.getElementById('my_span').innerHTML.replace(re, "<br>" );})();
Whereas this doesn't:
javascript:(function(){var re = new RegExp("
", "g"); document.getElementById('my_span').innerHTML=document.getElementById('my_span').innerHTML.replace(re, "<br>" );})();
Oddly the latter will take the first instance of
and just remove it without replacing it.
The page I'm working with does not load jQuery and I'm working in a corporate environment so I'm loathe to call something external.
Is this to do with with innerHTML not receiving the
as I expect it to? Thanks very much for your help.
It's exactly like you said: innerHTML is not receiving those characters as you expect it to. Inserting character entities into HTML causes them to be interpreted, and innerHTML returns the interpreted version, not the raw version. If you have:
<p id="test">Cookies & Cream</p>
and you use:
document.getElementById('test').innerHTML;
you don't get:
Cookies & Cream
you get:
Cookies & Cream
Similarly, when you're using innerHTML in your bookmarklet, you're not getting
: you're getting a carriage return and a line feed.
To match those characters with regex, use \r\n. \r will match the carriage return (
). While \n will match the line feed (&xa;).
var regex = new RegExp('\r\n', 'g');

Javascript Newline Character Throwing Error

I am having trouble getting some data from a textbox using javascript. What I am trying to do is take the value from a textbox and put it in an alert and copy it. Here is the code that I currently have:
var copyString = "Date: <%= TXT_Details_DateReq.Text %>;
window.prompt('Press CTRL+C, then ENTER\n\nNOTE: SAVE ANY CHANGES BEFORE COPYING TEXT!', copyString); return false;
So this code works perfectly fine if the text in the textbox is just one line. But if the text in the textbox has multiple lines such as:
"This is one line
here is a second line"
The code will throw the error Uncaught Syntax Error: Unexpected Token ILLEGAL.
From what I have researched this throws when there is an illegal character, so I believe it is the CRLF character from the textbox.
Any idea how to fix this?
Thanks.
New line characters might be preceded by return characters ('\r').
Swap '\n' with '\r\n' and you should be good to go.
Or even better: just handle all cases of the new line character instead of checking which case then applying it. This replace the newline:
htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
Resource
hope it helps.

Categories

Resources