peteb peteb - 4 months ago 16
Node.js Question

Pass newline character as argument to function

I'm trying to use a function to build a string based on a separator that is passed in as an argument. One of the separators is the

\n
character, passing in the newline character as an argument isn't outputting what I expected.

let concat = function(a, b, sep) {
return a + sep + b;
};

concat('Hello', 'World', '\n'); // Outputs 'Hello\nWorld'



Desired output:



Hello

World


How can I implement this so that I get my output string respecting the newline character escape notation instead of treating it as the string
'\n'
?

Answer

Try to print it (using console.log() as you mentioned), you'll see it works.

I checked it online to avoid been downvoted :) I generated some lame pre-formatted HTML to see if linefeed worked.

let concat = function(a, b, sep) {
  return a + sep + b;
};

document.writeln(concat('<PRE>Hello', 'World</PRE>', '\n'));

outputs

Hello
World

in the document

I don't know js, but if it's like python, values have different representations depending on if they're evaluated in the shell (or debugger) and displayed or explicitly printed. Can be frustrating sometimes.