693

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?

Example:

A variable passed from PHP as below:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

I would like my result to look something like this after the JavaScript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
5
  • 1
    Something wrong with your original question? stackoverflow.com/questions/784313/…
    – harto
    Apr 24, 2009 at 4:42
  • 1
    You could also do nl2br($string) in PHP before you send it to JavaScript.
    – alex
    Apr 24, 2009 at 4:44
  • 1
    I'm going to vote to close the earlier question, as this has a better example. Apr 24, 2009 at 4:48
  • 2
    He should edit the initial question then
    – nickf
    Apr 24, 2009 at 4:48
  • I came here from a misguided understanding to what was going on with .text(). See stackoverflow.com/q/35238362/1467396 if that's what you're doing, too
    – David
    Aug 14, 2019 at 21:54

14 Answers 14

1473

This will turn all returns into HTML

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

In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

15
  • 95
    Just additional note: str.replace("\n", '<br />') (first argument is a regular string) will replace only first occurrence.
    – Serge S.
    Apr 15, 2013 at 20:49
  • 23
    Another version (to replace multiple line-breaks): str.replace(/(\n)+/g, '<br />');
    – Ritesh
    Apr 16, 2013 at 16:30
  • 5
    @SergeS. Thanks for that extra comment. Just saved me a TONNE of time! jsfiddle Aug 11, 2013 at 3:37
  • 5
    @SergeS., String#replace coerces its first argument from String to an escaped RegExp instance, with no flags. str.replace('\n', '<br />'); is equivalent to str.replace(new RegExp('\n'), '<br />'); Jan 19, 2014 at 7:37
  • 4
    Here is a test case compare to str.split("\n").join("<br />") jsperf.com/split-join-vs-replace-regex RegEx seems slightly faster
    – Aley
    Jan 30, 2015 at 19:31
551

If your concern is just displaying linebreaks, you could do this with CSS.

<div style="white-space: pre-line">Some test
with linebreaks</div>

Jsfiddle: https://jsfiddle.net/5bvtL6do/2/

Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).

14
  • 18
    I came here looking for the regex and left with this. In lots of occasions this is what people are looking for. We use linebreaks for emails and need to display what the email looked line in html, sometimes. Perfecto. Thanks for looking at the question in a different light
    – O'Mutt
    Mar 1, 2016 at 19:01
  • 1
    This might work for actual line breaks, but what if I have "\n"s like in the question? Can I solve this by CSS, too?
    – Froxx
    May 24, 2016 at 10:13
  • 30
    Instead of white-space: pre-wrap; I prefer use white-space: pre-line; (to not add a final break line after all)
    – jpmottin
    Aug 9, 2016 at 17:54
  • 5
    looks good but what about a giant space before the first line? weird
    – Toolkit
    Feb 4, 2017 at 11:12
  • 4
    @jpmottin I think your version is closer to what the question author was looking for, so I changed my answer to white-space: pre-line as well. Thank you!
    – bersling
    Apr 12, 2020 at 7:22
87

Without regex:

str = str.split("\n").join("<br />");
5
  • 2
    If you do "\\n" you'll avoid issues with splitting on just the "n". Aug 2, 2012 at 19:19
  • 12
    @CrowderSoup hmm? I just tried it and \\n doesn't match on a new line, because it's looking for backslash + n. Aug 3, 2012 at 8:04
  • 1
    I made a test case. RegEx is slightly faster, but check out for yourself jsperf.com/split-join-vs-replace-regex
    – Aley
    Jan 30, 2015 at 19:29
  • I found this answer did not work unless the slash was escaped. For example: str = str.split("\n").join("<br />");
    – ACOMIT001
    Oct 29, 2015 at 8:15
  • 2
    @ACOMIT001 I guess that depends whether the string has a new line or a blackslash and n? Oct 29, 2015 at 8:57
46

This works for input coming from a textarea

str.replace(new RegExp('\r?\n','g'), '<br />');
2
13

If the accepted answer isn't working right for you then you might try.

str.replace(new RegExp('\n','g'), '<br />')

It worked for me.

3
  • 3
    new RegExp('\n', 'g') is identical to /\n/g (except for some minutiae about using primitive literals versus their constructors). Mar 10, 2013 at 9:37
  • 2
    whatever the reason, this worked for me but the accepted answer didn't
    – nick
    Mar 13, 2013 at 9:08
  • 1
    Ah, same here... but my mistake was attempting to specify /\n/g as a string! Mar 15, 2013 at 15:26
9

Shortest code supporting the most common EOL styles \r, \n, \r\n and using HTML5 <br>:

s.replace(/\r?\n|\r/g, '<br>')
8

Regardless of the system:

my_multiline_text.replace(/$/mg,'<br>');
2
  • 1
    Caution: This will append a '<br>' tag to any string, regardless if there's a ‘\n‘ in it.
    – mkoeller
    Oct 29, 2019 at 15:53
  • You could fix the error @mkoeller mentioned by adding this after the first replacement: .replace(/\<br\>$, ''), which will remove that last <br> ("search for <br> that touches the end of the string ($), and replace it with an empty string ('')") Jul 17, 2021 at 21:02
6

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'));
        }
    }
}
1
  • Like it but I don't have or want a target element. Can this be done where the return value is a string? Apr 12, 2021 at 20:27
5

This worked for me when value came from a TextBox:

string.replace(/\n|\r\n|\r/g, '<br/>');
3

For those of you who just want to allow max. 2 <br> in a row, you can use this:

let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');

First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br

Second line: Search for all single \r\n or \n and replace them with <br>

2

if you send the variable from PHP, you can obtain it with this before sending:

$string=nl2br($string);
1
  • This should be selected answer thanks for the simple straightforward answer .
    – Salem
    Jan 15, 2021 at 21:27
0

It will replace all new line with break

str = str.replace(/\n/g, '<br>')

If you want to replace all new line with single break line

str = str.replace(/\n*\n/g, '<br>')

Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.

1
  • It is also possible to use a regex like this str = str.replace(/\n+/g, '<br>') for the second case May 23, 2019 at 21:19
0

Not answering the specific question, but I am sure this will help someone...

If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:

var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
-1

I had a config in PHP that was being passed in from the Controller. (Laravel)

Example: PHP Config

'TEXT_MESSAGE' => 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'

Then in javascript using es6 reduce. notice I had to have two \\ or the output was not being replace correctly. Here are the parameters that are assoicated with the reduce function

  • previousValue (the value resulting from the previous call to callbackfn)
  • currentValue (the value of the current element)
  • currentIndex Optional
  • array (the array to traverse) Optional
//p is previousVal
//c is currentVal
String.prototype.newLineReplace = function(){
    return [...arguments].reduce((p,c) => p.replace(/\\n/g,c), this);
}

Here is how i used it in my script.

<script type="text/javascript">var config = @json($config);</script>

config.TEXT_MESSAGE.newLineReplace("<br />")

of course you could just called it on a javascript sring like...

let a = 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
var newA = a.newLineReplace("<br />")

//output
'From:Us<br />User: Call (1800) 999-9999<br />userID: %s'

Not the answer you're looking for? Browse other questions tagged or ask your own question.