Use PHP functions in JavaScript

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: 1109.2015
    // 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');
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Thomas
Jan 4th Permalink

q  The breakTag variable doesn't display correctly.

Gravatar
PJ Brunet
6 Sep '11 Permalink

q  Thanks for the clarification, indeed I was looking at the syntax highlighter version.

I'm about to try this function to workaround some .innerHTML issue I'm having.

Gravatar
Brett Zamir
5 Sep '11 Permalink

q  @PJ Brunet: Just avoid the 2nd argument (or pass true) (it's not showing in the syntax highlighter, but it's there if you look at the source). That's the PHP way too, which we try to stick to here...

Gravatar
PJ Brunet
4 Sep '11 Permalink

q  I'm voting for

<br />

vs. "br"

Gravatar
Dj
28 Jul '11 Permalink

q  Why not use first regex instead the second one? (without [^>\r\n]?)

return (str + '').replace(/(\r\n|\n\r|\r|\n)/g, breakTag + '$1');



return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');

Gravatar
Atttze
17 Feb '10 Permalink

q  In Firefox (maybe more browsers) the <br /> in the code block above at line 22 is 'hidden'...

Gravatar
Atttze
17 Feb '10 Permalink

q  According to the PHP docs it should be:

var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
';



Not:


var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '
';

Gravatar
Brett Zamir
14 Nov '09 Permalink

q  @Maximusya: Good catch--fixed in http://github.com/kvz/phpjs/commit/cc8835a98b175ad7038fcd64c85936f3bea8bdbb

Gravatar
Maximusya
13 Nov '09 Permalink

q  Taking into account different newline combinations (\r\n, \r, \n), function should return

return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');

Gravatar
Kevin van Zonneveld
14 Jan '09 Permalink

q  @ 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!

Gravatar
Brett Zamir
14 Jan '09 Permalink

q  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.

Gravatar
Brett Zamir
14 Jan '09 Permalink

q  HI John,

I think concerns on this range from &quot;What happens if a standard version gets implemented later?&quot; to &quot;Will this interfere with other implementations added to the prototype (as a kind of &quot;global&quot; problem?&quot;), 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).

Gravatar
John Peterson
14 Jan '09 Permalink

q  Why not just do this so much simplier...

String.prototype.nl2br = function() {
var breakTag = '&lt;br /&gt;';
return (this + '').replace(/([^&gt;]?)\n/g, '$1'+ breakTag +'\n');
}

then you can just do:

mystring.nl2br()

Gravatar
Kevin van Zonneveld
13 Oct '08 Permalink

q  @ 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.

Gravatar
Atli Þór
10 Oct '08 Permalink

q  Not sure why my last post got messed up like that.
If it was bad formatting on my part I apologize.

Gravatar
Atli Þór
10 Oct '08 Permalink

q  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:

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:


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');
}

Gravatar
Kevin van Zonneveld
29 Sep '08 Permalink

q  @ Onno Marsman: Nice :) Function has been updated according to your proposal!

Gravatar
Onno Marsman
26 Sep '08 Permalink

q  lol, still no good. Kevin: you know what I mean. I've only added (str+'')

Gravatar
Onno marsman
26 Sep '08 Permalink

q  I guess html is not escaped correctly, I meant:
[CODE=&quot;Javascript&quot;]
function nl2br( str ) {
return (str+'').replace(/([^&gt;])\n/g, '$1&amp;lt;br /&amp;gt;\n');
}
[/CODE]

Gravatar
Onno Marsman
26 Sep '08 Permalink

q  To make sure it's a string i.e. nl2br(6):

[CODE=&quot;Javascript&quot;]
function nl2br( str ) {
return (str+'').replace(/([^&gt;])\n/g, '$1&lt;br /&gt;\n');
}
[/CODE]

Gravatar
Music Russia
8 Sep '08 Permalink

q  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:

[CODE=&quot;Javascript&quot;]
var nfull = document.getElementById('full').value;
nfull = nfull.replace(/([^&gt;])\\n/g, '$1&lt;br /&gt;');
document.getElementById('txtpr').innerHTML = nfull;
[/CODE]

Thank you for the hint!

Gravatar
Kevin van Zonneveld
8 Sep '08 Permalink

q  @ Music Russia: Please be more specific, can you for example provide the code how you call it? And explain what breaks? Thanks a lot!

Gravatar
Music Russia
6 Sep '08 Permalink

q  Do not work in my case.

Gravatar
Kevin van Zonneveld
21 May '08 Permalink

q  @ Joshua: Thank you, we're still working on a tool to customize &amp; save your own php.js version, maybe that would be something for you then!

Gravatar
Joshua
21 May '08 Permalink

q  Nice piece of js code, very usefull :) I'm not using the whole package but just little pieces of code, great work!

Gravatar
Kevin van Zonneveld
15 Apr '08 Permalink

q  @ Philip Peterson: I've updated the function with your suggestions. Thank you!

Gravatar
Philip Peterson
15 Apr '08 Permalink

q  There are a few inconsistencies here:

first off, the replacement text should be &quot;&lt;br /&gt;\n&quot; (with the space before the backslash in &lt;br /&gt; 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.


Contribute a New function