12
In PHP, we can convert a line break to a <br/>
through function nl2br
.
What about Javascript? How can I do this safely?
I decided to ask the question because I don’t know if a simple replace("\n")
fits for all cases of line break.
12
In PHP, we can convert a line break to a <br/>
through function nl2br
.
What about Javascript? How can I do this safely?
I decided to ask the question because I don’t know if a simple replace("\n")
fits for all cases of line break.
14
There is a project in Github called php.js, which proposes to convert PHP functions into Javascript. They port 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:
https://stackoverflow.com/questions/7467840/nl2br-equivalent-in-javascript
10
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
I put in the Github for future reference.
Or you can use the tag without the bar.
Exactly! I was worried it would be more complex than a simple .replace("\n", '<br/>')
. Thanks :)
Browser other questions tagged javascript html string
You are not signed in. Login or sign up in order to post.
+1 for the xhtml ;)
– Wallace Maxters
I have nothing against the answer having more votes and having been accepted, I think she good, but this XHTML does not convince me. Why do this? If it is not for a human to read, it makes no difference. Choose a pattern and always use it. XHTML is obsolete. I put it in mine the way the AP put it in the question, but I would use my code one
<br>
which is the default of HTML 5 and which is accepted by all browsers.– Maniero