如何在 Javascript 连接字符串上强制换行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15357846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:30:57  来源:igfitidea点击:

How to force a line break on a Javascript concatenated string?

javascriptconcatenation

提问by blarg

I'm sending variables to a text box as a concatenated string so I can include multiple variables in on getElementById call.

我将变量作为连接字符串发送到文本框,因此我可以在 getElementById 调用中包含多个变量。

I need to specify a line break so the address is formatted properly.

我需要指定一个换行符,以便正确格式化地址。

document.getElementById("address_box").value = 
(title + address + address2 + address3 + address4);

I've already tried \n after the line break and after the variable. and tried changing the concatenation operator to +=.

我已经在换行符之后和变量之后尝试过 \n 。并尝试将连接运算符更改为 +=。

Fixed: This problem was resolved using;

已修复:此问题已解决;

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" +  address3 +  "\n" + address4);

and changing the textbox from 'input type' to 'textarea'

并将文本框从“输入类型”更改为“文本区域”

回答by Guffa

You can't have multiple lines in a text box, you need a textarea. Then it works with \nbetween the values.

一个文本框中不能有多行,你需要一个 textarea。然后它\n在值之间起作用。

回答by jnovack

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

回答by Chirag Bhatia - chirag64

You need to use \ninside quotes.

您需要使用\n内引号。

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\nis called a EOLor line-break, \nis a common EOLmarker and is commonly refereed to as LFor line-feed, it is a special ASCIIcharacter

\n被称为 a EOLor line-break\n是一个常见的EOL标记,通常被称为LFor line-feed,它是一个特殊ASCII字符

回答by Vahid Akhtar

Using Backtick

使用反引号

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

反引号通常用于多行字符串或当您想在字符串中插入表达式时

let title = 'John';
let address = 'address';
let address2 = 'address2222';
let address3 = 'address33333';
let address4 = 'address44444';
document.getElementById("address_box").innerText = `${title} 
${address}
${address2}
${address3} 
${address4}`;
<div id="address_box">
</div>