javascript - 如何将换行符/回车符插入到 element.textContent 中?

标签 javascript string escaping carriage-return

虽然听起来很傻,但我仍然没有找到合适的答案。

假设我想动态创建一个新的 DOM 元素并填充它的 textContent/innerText 使用 JS 字符串文字。
字符串太长了,我想把它分成三 block :

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

问题是,如果我写

h1.textContent = "...I would like to insert a carriage return here... \n";

它不起作用,可能是因为浏览器认为 '\n' 是纯文本并按原样显示它(\r 也不起作用)。

另一方面,我可以更改 h1.innerHTML 而不是 textContent 并编写:

h1.innerHTML = "...I would like to insert a carriage return here...<br />";

这里
可以完成这项工作,但这样做不仅会替换文本内容,还会替换我的 h1 的所有 HTML 内容,这不是我想要的
.

有没有一种简单的方法可以解决我的问题?
我不会为了让文本位于不同的行而创建多个 block 元素。
任何想法将不胜感激。
提前致谢。

最佳答案

我知道这个问题很久以前就发布了。

几天前我遇到了类似的问题,以 json 格式从 Web 服务传递值并将其放入 table cell contentText.

因为value是按格式传递的,比如"text row1\r\ntext row2"等等。

对于 textContent 中的新行,您必须使用 \r\n 最后,我不得不使用 css white-space: pre-line; (文本将在必要时换行,并在换行符处换行)一切正常。

或者,您可以仅使用 white-space: pre;,然后文本将仅在换行符处换行(在本例中为 \r\n)。

因此,有一个示例如何通过仅在换行符处换行来解决它:

var h1 = document.createElement("h1");

//setting this css style solving problem with new line in textContent
h1.setAttribute('style', 'white-space: pre;');

//add \r\n in text everywhere You want for line-break (new line)
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";
h1.textContent += "so this text will display in a new line";

document.body.appendChild(h1);

关于javascript - 如何将换行符/回车符插入到 element.textContent 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980416/

相关文章:

string - 字符串连接的 '+' 和 '&' 之间有什么区别吗?

linux - 如何转义 ip link 命令的特殊字符设备名称

javascript - 使 javascript 文件了解其 typescript 定义文件

javascript - 每个用户/产品的新 html、css、js 页面

c - 获取包含十六进制值的 LPTSTR 或 CHAR* 的大小

python - 为什么在终端和运行终端的程序中内联打印转义的十六进制字符之间存在差异?

在 rpm 规范文件中转义

javascript - 为什么在对同一变量使用 'hidden' 和 'button' 输入时得到 2 个相等的 html GET 参数?

javascript - 将值推送到匿名数组

python - 将字符串数组中的元素输出到句子