How can I turn line breaks into br / in JavaScript?

11

In PHP, we can convert a line break to a <br/> through the function nl2br .

What about JavaScript? How can I do this in a secure way?

I decided to ask the question because I do not know if a simple replace("\n") fits all cases of line break.

    
asked by anonymous 13.10.2015 / 15:36

2 answers

12

There is a project in GitHub called php.js, which aims to convert PHP functions into Javascript. They performed this function as follows:

function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}   

Sources:
link

link

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

Font .

Or you can use tag without the bar .

    
13.10.2015 / 15:41