如何在 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
How to force a line break on a Javascript concatenated string?
提问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 \n
between 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 \n
inside 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)
\n
is called a EOL
or line-break
, \n
is a common EOL
marker and is commonly refereed to as LF
or line-feed
, it is a special ASCII
character
\n
被称为 a EOL
or line-break
,\n
是一个常见的EOL
标记,通常被称为LF
or 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>