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.
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.
Share Improve this question asked Dec 17, 2018 at 14:00 KhalilKhalil 1,1074 gold badges17 silver badges35 bronze badges 4- 1 just use back ticks for multiline strings. – Jai Commented Dec 17, 2018 at 14:01
- I can do that but I want to know if I can add line breaks in object – Khalil Commented Dec 17, 2018 at 14:03
-
3
Depending on your environment, you may want to switch to
console.table({ value : "Foo\nBar" });
. – Álvaro González Commented Dec 17, 2018 at 14:03 -
The output of
console
logging is implementation-dependant. – str Commented Dec 17, 2018 at 14:10
4 Answers
Reset to default 3The 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.)
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.
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
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world