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

前端 未结 13 2316
刺人心
刺人心 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:22

    Without regex:

    str = str.split("\n").join("<br />");
    
    0 讨论(0)
  • 2020-11-22 02:22

    For those of you who just want to allow max. 2 <br> in a row, you can use this:

    let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
    text = text.replace(/(\r?\n)/g, '<br>');
    

    First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br

    Second line: Search for all single \r\n or \n and replace them with <br>

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

    Regardless of the system:

    my_multiline_text.replace(/$/mg,'<br>');
    
    0 讨论(0)
  • 2020-11-22 02:24

    This worked for me when value came from a TextBox:

    string.replace(/\n|\r\n|\r/g, '<br/>');
    
    0 讨论(0)
  • 2020-11-22 02:28

    Not answering the specific question, but I am sure this will help someone...

    If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:

    var text_with_line_breaks = retrieve_some_text_from_php();
    var element = document.querySelectorAll('#output');
    element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
    
    0 讨论(0)
  • 2020-11-22 02:32

    It is also important to encode the rest of the text in order to protect from possible script injection attacks

    function insertTextWithLineBreaks(text, targetElement) {
        var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
        var textParts = textWithNormalizedLineBreaks.split('\n');
    
        for (var i = 0; i < textParts.length; i++) {
            targetElement.appendChild(document.createTextNode(textParts[i]));
            if (i < textParts.length - 1) {
                targetElement.appendChild(document.createElement('br'));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题