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

前端 未结 13 2546
刺人心
刺人心 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: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'));
            }
        }
    }
    

提交回复
热议问题