javascript将\ n替换为< br>在createTextNode里面

问题描述:

我有一个带 \ n 的字符串-Java脚本中的换行符,我想使用Javascript中的 createTextNode()替换另一个文本.

I have a String with \n - line breaks in Javascript, that I want to replace for another text using createTextNode() in Javascript.

<script type="text/javascript">

function changeText() {

var Explanation="Test\n Test2";

var parent3 = document.getElementById("The_Explanation"); 
parent3.innerHTML='';  
var myP3 = document.createElement("p");
var myText3 = document.createTextNode(""+Explanation);
myP3.appendChild(myText3);
parent3.appendChild(myP3);
}
</script>

到目前为止,所有尝试将换行符插入新文本都失败了.将 \ n 替换为< br> 的所有函数只会把我带到结果

All tries to get the line break into the new text failed so far. All functions that replace \n to <br> only bring me to the result

"Test<br> Test2"

有任何想法吗?

您不能将元素节点放在文本节点内.文本节点不能有子节点.

You can't put an element node inside a text node. Text nodes cannot have child nodes.

  1. 将字符串拆分为新行
  2. 遍历数组并为每个部分生成一个文本节点
  3. 使用 createElement('br')创建一个换行符,以在每个文本节点之间移动
  4. 附加以上所有内容
  1. Split your string on new lines
  2. Loop over the array and generate a text node for each part
  3. Use createElement('br') to create a line break to go between each text node
  4. append all of the above