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