How do I replace all line breaks in a string with
elements?

前端 未结 13 2317
刺人心
刺人心 2020-11-22 02:00

How can I read the line break from a value with JavaScript and replace all the line breaks with
elements?

Example:

A variable passe

相关标签:
13条回答
  • 2020-11-22 02:34

    If your concern is just displaying linebreaks, you could do this with CSS.

    <div style="white-space: pre-line">Some test
    with linebreaks</div>
    

    Jsfiddle: https://jsfiddle.net/5bvtL6do/2/

    Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).

    0 讨论(0)
  • 2020-11-22 02:35

    This will turn all returns into HTML

    str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
    

    In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
    https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

    0 讨论(0)
  • 2020-11-22 02:35

    It will replace all new line with break

    str = str.replace(/\n/g, '<br>')

    If you want to replace all new line with single break line

    str = str.replace(/\n*\n/g, '<br>')

    Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.

    0 讨论(0)
  • 2020-11-22 02:37

    Try

    let s=`This is man.
    
         Man like dog.
         Man like to drink.
    
         Man is the king.`;
         
    msg.innerHTML = s.replace(/\n/g,"<br />");
    <div id="msg"></div>

    0 讨论(0)
  • 2020-11-22 02:39

    If the accepted answer isn't working right for you then you might try.

    str.replace(new RegExp('\n','g'), '<br />')
    

    It worked for me.

    0 讨论(0)
  • 2020-11-22 02:46

    This works for input coming from a textarea

    str.replace(new RegExp('\r?\n','g'), '<br />');
    
    0 讨论(0)
提交回复
热议问题