JavaScript nl2br
Converts newlines to HTML line breaks
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 | function nl2br (str, is_xhtml) { // Converts newlines to HTML line breaks // // version: 911.1619 // discuss at: http://phpjs.org/functions/nl2br // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Philip Peterson // + improved by: Onno Marsman // + improved by: Atli Þór // + bugfixed by: Onno Marsman // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Maximusya // * example 1: nl2br('Kevin\nvan\nZonneveld'); // * returns 1: 'Kevin\nvan\nZonneveld' // * example 2: nl2br("\nOne\nTwo\n\nThree\n", false); // * returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n' // * example 3: nl2br("\nOne\nTwo\n\nThree\n", true); // * returns 3: '\nOne\nTwo\n\nThree\n' var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); } |
Examples
» Example 1
Running
1 | nl2br('Kevin\nvan\nZonneveld'); |
Should return
1 | 'Kevin\nvan\nZonneveld' |
» Example 2
Running
1 | nl2br("\nOne\nTwo\n\nThree\n", false); |
Should return
1 | '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have nl2br goodness in JavaScript.
According to the PHP docs it should be:
1 | var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>'; |
Not:
1 | var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>'; |
@Maximusya: Good catch--fixed in http://github.com/kvz/phpjs/commit/cc8835a98b175ad7038fcd64c85936f3bea8bdbb
Taking into account different newline combinations (\r\n, \r, \n), function should return
1 | return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); |
@ John Peterson: Of course: that's not at all like PHP. And that's what we're trying to recreate here: So the main version should be as is it right now.
However. Just like there's a namespaced version of PHP.JS, I think it should be possible for us to generate prototype versions with the compiler.
Currently this is a low priority for me and I would first like to create a public interface to the compiler on the phpjs.org site.
But I will keep this in mind as a future feature!
I should add the extra qualification that overloading the Object or Array prototype would probably be quite objectionable to many and need some serious revising of the PHP-JS functions (which I'm thinking should probably be revised regardless) to check for hasOwnProperty in each iterating for loop.
HI John,
I think concerns on this range from "What happens if a standard version gets implemented later?" to "Will this interfere with other implementations added to the prototype (as a kind of "global" problem?"), etc.. However, I personally think this could be very convenient for those willing to take the risk (or who reset the prototype after their code is done with it).
Maybe when we get the string functions done ( ;) ), we can make one version of the PHP-JS package which adds to the prototype (also for Array, Object, Number, or maybe Function or Boolean if you can think of a reason!), as I'm hoping we can see a configurable version made at some point (as an independent project, if not through Kevin's official version).
Why not just do this so much simplier...
String.prototype.nl2br = function() {
var breakTag = '<br />';
return (this + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}
then you can just do:
mystring.nl2br()
@ Atli Þór: That's a Great contribution Atli Þór. I wish I could give your more credit, than the current system can give you. Thanks man.
Hi.
There seems to be a minor flaw in the function for strings that start with a line-breaks, or have multiple consecutive line-breaks.
Using this:
[code="text"]nl2br("\nOne\nTwo\n\nThree\n")[/code]
it leaves out the first new-line and replaces the two new-lines between "Two" and "Three" with a single break.
Making the regex non-greedy seems to fix this tho:
1 | return (str + '').replace(/([^>]?)\n/g, '$1<br />\n'); |
Additionally, PHP 5.3 will accept a second parameter, indicating whether the break should be XHTML compliant or not.
This would allow for that as well:
1
2
3
4
56
7
| function nl2br( str, is_xhtml ) { breakTag = "<br />"; if(typeof is_xhtml == "boolean" || is_xhtml == false) { breakTag = "<br>"; } return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n'); } |
I guess html is not escaped correctly, I meant:
1 2 3 | function nl2br( str ) { return (str+'').replace(/([^>])\n/g, '$1&lt;br /&gt;\n'); } |
To make sure it's a string i.e. nl2br(6):
1 2 3 | function nl2br( str ) { return (str+'').replace(/([^>])\n/g, '$1<br />\n'); } |
Sorry, Kevin, that's just my stupid mistake, i confused one var with another. I spend about 15 minutes until figured it out.
Here's the part of my code and it 100% works now:
1 2 3 | var nfull = document.getElementById('full').value; nfull = nfull.replace(/([^>])\\n/g, '$1<br />'); document.getElementById('txtpr').innerHTML = nfull; |
Thank you for the hint!
@ Music Russia: Please be more specific, can you for example provide the code how you call it? And explain what breaks? Thanks a lot!
@ Joshua: Thank you, we're still working on a tool to customize & save your own php.js version, maybe that would be something for you then!
Nice piece of js code, very usefull :) I'm not using the whole package but just little pieces of code, great work!
There are a few inconsistencies here:
first off, the replacement text should be "<br />\n" (with the space before the backslash in <br /> and including the newline). Also, I don't have time to do this, but you may want to check out how PHP handles \r\n and \r in this function, as it may be useful to implement support for if the PHP function does it.


Atttze
Feb 17th
in the code block above at line 22 is 'hidden'...