How can I insert new line/carriage returns into an element.textContent?

前端 未结 9 2117
野的像风
野的像风 2020-11-27 14:44

As silly as it may sound, I still haven\'t found an appropriate answer.

Let\'s say I want to dynamically create a new DOM element and fill up its textContent/innerTe

9条回答
  •  [愿得一人]
    2020-11-27 15:19

    You could use regular expressions to replace the '\n' or '\n\r' characters with '
    '.

    you have this:

    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";
    

    you can replace your characters like this:

    h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '
    ');

    check the javascript reference for the String and Regex objects:

    http://www.w3schools.com/jsref/jsref_replace.asp

    http://www.w3schools.com/jsref/jsref_obj_regexp.asp

提交回复
热议问题