在javascript中,如何在控制台中显示行尾字符的字符串,并保持“ \ n”

时间:2019-01-23 09:08:07

标签: javascript

console.log用于包含行尾字符的字符串时,该字符串会分成几行。

我想用“ \ n”字符在控制台上显示屏幕,而无需修改输入字符串。

例如:

let myLines = "Hello\nWorld";
console.log(myLines)
Hello
World

我希望输出为:"Hello\nWorld"

4 个答案:

答案 0 :(得分:3)

您可以使用正则表达式用文字反斜杠后跟n替换换行符:

let myLines = "Hello\nWorld";
console.log(myLines.replace(/\n/g, '\\n'));

答案 1 :(得分:1)

如果可接受额外的引号,则可以使用JSON输出(或修剪引号):

let myLines = "Hello\nWorld";
console.log(JSON.stringify(myLines));
console.log(JSON.stringify(myLines).replace(/^"|"$/g, ''));
"Hello\nWorld"
Hello\nWorld

答案 2 :(得分:0)

它将起作用

let myLines = "Hello\nWorld"
console.log(myLines.replace('\n','\\n'));

答案 3 :(得分:-1)

只需在\ n之前添加反斜杠:

D/BluetoothGatt( 6359): connect() - device: 73:B9:9F:25:67:DC, auto: true
D/BluetoothGatt( 6359): registerApp()
D/BluetoothGatt( 6359): registerApp() - UUID=44fdc1ff-3804-4ae2-ab52-3f3b6eb31e17
D/BluetoothGatt( 6359): onClientRegistered() - status=0 clientIf=7
D/BluetoothGatt( 6359): onAutoConnectionStatusCb()status =10
D/BluetoothGatt( 6359): close()