最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - LineBreak in console object - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 3

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

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
发布评论

评论列表(0)

  1. 暂无评论