How do I replace all line breaks in a string with <br /> elements?

Viewed 597677

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."
14 Answers

This works for input coming from a textarea

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

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

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

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.

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

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'
Related