Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 605
Tzn Avatar asked Mar 23 '18 18:03

Tzn


2 Answers

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?

like image 152
pourmesomecode Avatar answered Sep 21 '22 19:09

pourmesomecode


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:

chrome's console with original source

(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.

like image 25
Gilad Avatar answered Sep 18 '22 19:09

Gilad