Khalil
Khalil

Reputation: 1107

LineBreak in console object

Line break in javascipt string console

console.log("Foo" + "\n" + "Bar");

Line break in javascript object console

console.log({ value : "Foo\nBar" });

Is it possible to add linebreaks in javascript objects.

Upvotes: 2

Views: 4806

Answers (4)

Alex Barker
Alex Barker

Reputation: 21

You can make JSON pretty with automatic line breaks using:

console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))

Where 2 is the number of spaces/indent for each level.

Upvotes: 2

Elliot Nelson
Elliot Nelson

Reputation: 11557

The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).

If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:

function customString(object) {
    let string = '{\n';
    Object.keys(object).forEach(key => {
        string += '  "' + key + '": "' + object[key] + '"\n';
    });
    string += '}';
    return string;
}

console.log(customString({ value: "Foo\nBar" }));

(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)

Upvotes: 3

Steven Scaffidi
Steven Scaffidi

Reputation: 2307

You can use ES6:

console.log(`hello
world`)

will produce:

hello
world

Upvotes: 0

Mehmood
Mehmood

Reputation: 931

I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.

Code:

var v = {val:"test\ntest"};
console.log(v.val);

Output:

 test
test

Upvotes: 0

Related Questions