javascript Replacing \n with <br> inside createTextNode

元气小坏坏 提交于 2021-02-05 05:52:06

问题


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>

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"

Any ideas anyone?


回答1:


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

  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



回答2:


You can use replace for that:

   Explanation.replace( /\n/g, "<br />" )l


来源:https://stackoverflow.com/questions/13511809/javascript-replacing-n-with-br-inside-createtextnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!