Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log Stripping Carriage Returns (displaying as a literal ↵)

I'm trying to write a JavaScript function that prints a string to the console via console.log. However, the string has carriage returns in it, which show up as a literal ↵ character instead of creating a new line. Is this a limitation of console.log, or is there a way around this?

Thanks!

Edit: I'm actually trying to print this function inside an object. Something like:

function blah() {
};
console.log({ "function" : blah });

I didn't think to mention it initially, but after trying crowjonah's solution I realize that console.log apparently treats strings passed directly differently from strings passed inside another object.

like image 929
Jake Lazaroff Avatar asked Nov 27 '12 17:11

Jake Lazaroff


People also ask

What is return type of console log?

console. log(" "); Parameters: It accepts a parameter that can be an array, an object, or any message. Return value: It returns the value of the parameter given.

How do I stop the console log from printing a new line?

But sometimes we may need to print the console without trailing newline. In that case, we can use process. stdout. write() method to print to console without trailing newline.

What is carriage return in ascii?

In ASCII and Unicode, the carriage return is defined as 13 (or hexadecimal 0D); it may also be seen as control+M or ^M. In the C programming language, and many other languages (including regular expression) influenced by it, \r denotes this character.

How do I use the console to log into a different line?

To display a console. log in multiple lines we need to break the line with \n console. log("Hello \n world!"); That will display it like this: Hello world!


2 Answers

Chrome will render \n as when printing objects that contain multi-line strings. However, you can simply double-click on the logged string to see it with proper newlines.

like image 162
hughes Avatar answered Sep 29 '22 22:09

hughes


This is a limitation of console. but you can create a work around:

function multiLineLog(msg) {
    msg = msg.split(/[\r\n]+/g);
    for (var a=0; a < msg.length; a++) console.log(msg[a]);
}
like image 20
SReject Avatar answered Sep 29 '22 21:09

SReject